in Web & Tech

Keep navigation bar fixed after scrolling to a certain element

Say you want to tack younav bar fixed at the top of the browser’s viewport after a user has scrolled to a certain element in the DOM. In my example this is the menu itself. This snippet checks the vertical position of my main menu and adds a class to it after a visitor has been scrolling that far that it reached the top of the page.

$(document).ready(function() {
  var navpos = $('#mainnav').offset();
  console.log(navpos.top);
    $(window).bind('scroll', function() {
      if ($(window).scrollTop() > navpos.top) {
        $('#mainnav').addClass('fixed');
       }
       else {
         $('#mainnav').removeClass('fixed');
       }
    });
});

Source

Write a Comment

Comment

  • Related Content by Tag