Create a sticky menu using jQuery

Posted date: Jun 25, 2022

Javascript Jquery

In this tutorial will describe how to make a menu bar sticky and appear on scrolling.

Assuming that you have already created your menu bar using HTML/CSS you can add a few lines of javascript code to make it “Sticky” improving UIthe of your website.

For this task we will make use of the scroll event

Javascript Code snippet example

    window.addEventListener("scroll", e => {
        scrollPos = window.scrollY;
        if (scrollPos != 0) {
            $('#yourCssSelector').addClass('fixed');
        } else {
            $('#yourCssSelector').removeClass('fixed')
        }
    });

CSS to apply sticky functionality

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