A lightweight (2kb gzipped), zero-dependency, javascript library for creating float sidebars. Based on the finite state machine pattern.
The library is based on the finite state machine pattern that led to a more simple and reliable solution. Read more in the article on medium (in Russian)
npm install float-sidebar
or
yarn add float-sidebar
or
<script src="./path/to/float-sidebar.min.js"></script>
<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();
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. |
Method | Description |
---|---|
forceUpdate() | Recalculates all the dimensions and finally updates the position of the sidebar. |
destroy() | Disposes the DOM listeners. |
FloatSidebar.js is released under the MIT license.
Author Sergey Vinogradov