How to make a scrolling sticky sidebar
In this post we’re going to talk about how to make a scrollable sticky sidebar that auto stop when reaching the bottom. (A sidebar that scroll along with main content normally but become “sticky” or “fixed” when reaching the end of sidebar)
And today’s tutorial we’re going to work on it using only vanilla JavaScript
Content and Sidebar Setup
And here is the example page we’re going to work on. A flex display, two columns. One is main content and another one is side bar. (And in this case the sidebar has less content than the main div)
We want to make the sidebar stop scrolling and become sticky when users scrolled to the end of sidebar
First thing we’re going to do is to add a div to wrap the content of the sidebar. You won’t have to do this if your website already has a wrapper.
<div class="sidebar"> <div class="content-wrapper"> <!-- content --> <div></div> <div></div> <div></div> <div></div> </div> </div>
Next we’ll work on the JavaScript
Detecting Sidebar Position
First we’ll get the sidebar using getElementsByclassName and get the sidebar content wrapper.
let sidebar = document.getElementsByClassName("sidebar")[0]; let sidebar_content = document.getElementsByClassName("content-wrapper")[0];
Now inside the scroll event which will trigger every time when user scroll, we’ll need to get 4 values.
window.onscroll = () => { let scrollTop = window.scrollY; // current scroll position let viewportHeight = window.innerHeight; //viewport height let contentHeight = sidebar_content.getBoundingClientRect().height; // current content height let sidebarTop = sidebar.getBoundingClientRect().top + window.pageYOffset; //distance from top to sidebar }
So in order to know when user already scroll to the end of the sidebar content, we’ll check if the current scroll position larger than the contentHeight minus by the viewportheight and offset by top position
if(scrollTop >= contentHeight - viewportHeight + sidebarTop)
Then add the fixed position to the sidebar wrapper to make it become sticky. However, once the fixed position was added, it will also revert the position back to the top. To fix this will add a negative translateY to move the content up (use the same value as the if condition)
if(scrollTop >= contentHeight - viewportHeight + sidebarTop) { sidebar_content.style.transform = `translateY(-${contentHeight - viewportHeight + sidebarTop}px)`; sidebar_content.style.position = "fixed"; } else { sidebar_content.style.transform = ""; sidebar_content.style.position = ""; }
And that’s all for this tutorial. You can download the source code here. I also have the jQuery version for this code too. And it’s much easier to read and code if you don’t mind adding the library to your project as dependencies.
That's all for this tutorial. If you like it, check out our YouTube channel and our Twitter to stay tune for more dev tips and tutorials