Skip to content

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

<divclass="wrapper"><divclass="content"><!-- Content --></div><divclass="sidebar"><divclass="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;
}
importFloatSidebarfrom'float-sidebar';constsidebar=document.querySelector('.sidebar');constrelative=document.querySelector('.content');constfloatSidebar=FloatSidebar({
sidebar,
relative,topSpacing: 20,bottomSpacing: 20,});// ...floatSidebar.forceUpdate();// ...floatSidebar.destroy();

Options

NameTypeDefaultDescription
sidebarHTMLElementRequiredThe sidebar element
relativeHTMLElementRequiredThe sidebar relative element, e.g. the main content
viewportHTMLElementwindowThe viewport element
sidebarInnerHTMLElementsidebar.firstElementChildThe sidebar inner element
topSpacingnumber0The space from the top of the viewport. Used when the sidebar is in fixed state.
bottomSpacingnumber0The space from the bottom of the viewport. Used when the sidebar is in fixed state.

Instance API

MethodDescription
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

Stars

91 stars

Watchers

5 watching

Forks

Releases

Used by

Contributors

Languages