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');
       }
    });
});

Demo: https://dl.dropboxusercontent.com/u/1219657/demos/menu-fixed/index.html
Original source: http://stackoverflow.com/questions/13274592/leave-menu-bar-fixed-on-top-...

Tags: 

Need a great new website or a helping hand with Drupal? Head over to www.klickreflex.de or contact me directly to see if we can work something out.