FloatSidebar.js
FloatSidebar.js copied to clipboard
A lightweight (2kb gzipped), zero-dependency javascript library for making a sidebar float.
FloatSidebar.js
A lightweight (2kb gzipped), zero-dependency javascript library for making a sidebar float.
FloatSidebar.js is a vanilla javascript library that can be used to make a sidebar float, so it would automatically stick to the top or bottom of the viewport depending on the scroll direction as long as the beginning or end of the content is not reached.
The library supports two strategies which are enabled depending on the sidebar's height:
- When the sidebar's height > the viewport's height, the sidebar sticks to the viewport bottom when scrolling down, and to the viewport top when scrolling up (see the left sidebar on the video).
- When the sidebar's height < the viewport's height, the sidebar sticks to the viewport top (see the right sidebar on the video).
https://user-images.githubusercontent.com/5039436/164990489-0424b5ab-c231-4f5c-bc1b-fc3f9594e347.mov
Install
npm install float-sidebar --save
or
yarn add float-sidebar
or
<script src="./path/to/float-sidebar.min.js"></script>
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 in case of using an 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. It is used when the sidebar is fixed. |
| bottomSpacing | number |
0 |
The space from the bottom of the viewport. It is used when the sidebar is fixed. |
Instance API
| Method | Description |
|---|---|
| forceUpdate() | Recalculates all the dimensions and finally updates the position of the sidebar. |
| destroy() | Disposes the DOM listeners. |
Similar libraries
- https://github.com/abouolia/sticky-sidebar
License
FloatSidebar.js is released under the MIT license.
Author Sergey Vinogradov