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.)

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.