How to Build a Sticky Sidebar on Page Scroll With ScrollMagic.js

In this tutorial we’ll use ScrollMagic.js, a hugely popular JavaScript library, to build a sidebar that becomes sticky on page scroll. In three steps (HTML, CSS, and JavaScript) we’ll outline the whole process.

Here’s what we’re going to create (check out the full screen version to experience its full magic and give it some ♥):

serverpoint hosting banner

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:

“The javascript library for magical scroll interactions.”

Created by Jan Paepke, it can be effectively combined with the Greensock Animation Platform (GSAP) for building complex and attractive JavaScript animations. To better understand the capabilities of ScrollMagic, check out this list of examples and take a look at these tutorials and courses on Tuts+.

Getting Started With ScrollMagic.js

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). 

For our demo, we’ll choose the last option. With that in mind, if you look under the Settings tab of our demo pen, you’ll see that I’ve included one external JavaScript file:

Demo Set Up

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.

Here’s the markup:

2. The CSS

We won’t define any special styles for our example. Interestingly though, we use CSS grid to layout the post content’s on medium screens and up (≤768px) .

Here’s part of the CSS:

You might also like More from author

Leave A Reply

Your email address will not be published.