How to Build a Sticky Sidebar on Page Scroll With ScrollMagic.js
Here’s what we’re going to create (check out the full screen version to experience its full magic and give it some ♥):
The sidebar will be pinned only when the browser window is at least 768px wide and it reaches the top edge of the viewport. Smaller screens experienced a stacked layout instead.
What is ScrollMagic.js?
For the best description of ScrollMagic, we’ll head over to its Github page:
To get started with ScrollMagic, you first have to include it in your projects. You can download it by visiting its GitHub repo, by using a package manager (e.g. npm), or by loading the necessary assets through a CDN (e.g. cdnjs).
I’ve also incorporated Babel for compiling the ES6 code down to ES5.
1. The HTML
Our HTML consists of two helper sections and a post. The post contains two sub-sections: the post’s details and the post’s sidebar. In a real scenario the post’s contents could correspond to a blog post, a hotel room, or a school program.
Next, we create a scene with custom options and add it to the controller.
If the window’s width is at least 768px and the sidebar reaches the top edge of the viewport, we pin it for a duration defined in the scene. In our case, the desired duration is calculated by subtracting the post’s details height from the height of the sidebar’s contents.
As the window gets resized, we check its width. If it’s narrower than 768px, the sidebar remains part of the normal document flow, otherwise it becomes sticky.
4. Browser Support
The plugin itself has great browser support. Beyond the plugin’s support, our demo makes use of CSS Grid, so it will only work in browsers that support this layout method.
In this tutorial, we managed to build a sidebar that becomes sticky as we scroll down the page. Our basic implementation isn’t the most powerful thing you can build with this amazing library, but hopefully useful enough to take advantage of it in an upcoming project.
Lastly, if you’re familiar with any other more effective ScrollMagic approaches for building our demo, let us know in the comments below.