Skip to content

A lightweight (2kb gzipped), zero-dependency javascript library for making a sidebar float.

License

Notifications You must be signed in to change notification settings

vursen/FloatSidebar.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

72 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NPM version

FloatSidebar.js is a lightweight (2kb gzipped), zero-dependency JavaScript library that creates sticky, floating sidebars. It keeps the sidebar visible in the viewport by dynamically sticking it to the top or bottom based on scroll direction and sidebar height.

  • When the sidebar is taller than the viewport, it scrolls with the content, sticking to the bottom when scrolling down and to the top when scrolling up.
  • When the sidebar is shorter than the viewport: it stays fixed at the top during scrolling.
Example.mov

Demo

Install

npm install float-sidebar --save

or

yarn add float-sidebar

Usage

<div class="wrapper">
  <div class="content">
    <!-- Content -->
  </div>

  <div class="sidebar">
    <div class="sidebar__inner">
      <!-- Sidebar content -->
    </div>
  </div>
</div>
.wrapper {
  display: flex;
  /* Required when using infinite scroll */
  align-items: flex-start;
}

.sidebar {
  /* Required */
  position: relative;

  /* Required. The sidebar element should have a fixed width */
  width: 220px;
}
import FloatSidebar from 'float-sidebar';

const sidebar = document.querySelector('.sidebar');
const relative = document.querySelector('.content');

const floatSidebar = FloatSidebar({
  sidebar,
  relative,
  topSpacing: 20,
  bottomSpacing: 20,
});

// ...

floatSidebar.forceUpdate();

// ...

floatSidebar.destroy();

Options

Name Type Default Description
sidebar HTMLElement Required The sidebar element
relative HTMLElement Required The sidebar relative element, e.g. the main content
viewport HTMLElement window The viewport element
sidebarInner HTMLElement sidebar.firstElementChild The sidebar inner element
topSpacing number 0 The space from the top of the viewport. Used when the sidebar is in fixed state.
bottomSpacing number 0 The space from the bottom of the viewport. Used when the sidebar is in fixed state.

Instance API

Method Description
forceUpdate() Recalculates the dimensions and updates the sidebar's position
destroy() Cleans up DOM references and listeners

Similar libraries

License

FloatSidebar.js is released under the MIT license.

Author Sergey Vinogradov

About

A lightweight (2kb gzipped), zero-dependency javascript library for making a sidebar float.

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •