Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Fixed header on scroll

David Carr

Javascript CSS Tutorials

    A common web trend is to allow a static header stick to the top of the page when scrolling the page. I imagined there would be quite a bit to it but it turns out it’s very easy to accomplish.

    First create a css class, this will set the element to be fixed in place.

    .navbar-fixed {
      top: 0;
      z-index: 100;
      position: fixed;
      width: 100%;
    }

    Next add the following jQuery code:

    var navpos = $('#header').offset();
    $(window).bind('scroll', function() {
      if ($(window).scrollTop() > navpos.top) {
        $('#header').addClass('navbar-fixed');
      } else {
        $('#header').removeClass('navbar-fixed');
      }
    });

    This works by created a navpos var that holds the heigh of the element, then using bind on scroll to run a function that determined if the scroll is higher then the height of the element. When that is true give the element a class of navbar-fixed otherwise remove the class.

    To see this in action scroll on this blog to see the header move with the page. (Only when running on a normal desktop view so no mobile support.)

    Laravel Modules Book by David Carr

    Help support the blog so that I can continue creating new content!

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

    © 2009 - 2022 DC Blog. All code MIT license. All rights reserved.