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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn More)

  • Related Content by Tag