JavaScript: fixed header during scroll

JavaScript: fixed header during scroll

In this article we're going to make an header fixed when scrolling by using JavaScript.

In this article we're going to make an header fixed when scrolling by using JavaScript.

Let's start by defining a CSS class whose styles make the header fixed.


.fixed {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
}

Now we can create the main JavaScript code:


'use strict';

const siteHeader = document.getElementById('masthead');
const siteHeaderHeight = siteHeader.offsetHeight;

window.addEventListener('scroll', () => {
    const top = document.documentElement.scrollTop || document.body.scrollTop;
    if(top > siteHeaderHeight) {
        siteHeader.classList.add('fixed');
    } else {
        siteHeader.classList.remove('fixed');
    }
}, false);

top stores the current scroll value. If such a value is greater than the header's height, we can apply our CSS class to it. Otherwise, our header will be kept as a static element by removing the relevant CSS class.