Javascript | CSS | Tutorials

David Carr

Fixed header on scroll

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

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

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