Understanding Bootstrap’s Affix and ScrollSpy plugins

One of the things you probably have noticed when you visit Bootstrap’s website is the right-side navigation that moves as you scroll through the page. This scrolling effect can be achieved combining the Affix and ScrollSpy jQuery plugins, both available as Bootstrap components.

Bootstrap's docs nav

In this article, I’ll show you how to add this cool feature to one of your own projects. As always, to better demonstrate these, I’ll use a demo project.

Let’s start by taking a look at the HTML structure of it.

The Basic Markup for Our Demo

For small screens we use a single column layout. For medium and large screens our layout will consist of two columns. On the one hand, we have the navigation, which occupies one quarter of a row’s width. On the other hand, we have the main content sections, which occupy the other three quarters of a row’s width. Each of these sections has an id attribute value that matches the href attribute value of the corresponding anchor (a) element.

In our example, we want the scrolling effect to occur only when the viewport exceeds 991px (i.e. medium and large screens). For this reason, we add the hidden-xs and hidden-sm helper classes to the navigation.

See the code below. Note that for brevity, we’re not including content that isn’t relevant to the technique.