Simple Fixed Header Javascript/CSS

I’ve done several post on fixed headers. I get a lot of emails about them and a lot of site traffic. Obviously, a lot of people find them useful. So I’m going to post the simplest way that I know to make one. Be it in Drupal or WordPress, or even flat-file sites; this is the easiest way that I do fixed headers.

Below you’ll see some javascript. Take a look at it and then I’ll explain.

$(function () {
	//store the element
	var $top = $('.navigation-wrap');

	//store the initial position of the element
	$(window).scroll(function(){
	    if($(document).scrollTop() > 200) {
		  // if so, add the fixed class
		  $top.addClass('fixed');
		} else {
		  // otherwise remove it
		  $top.removeClass('fixed');
		}
	});
});

The first line is the basic shorthand document ready jquery opening. So we’ll skip to the next few lines.

var $top = $('.navigation-wrap');

Where you see ‘.navigation-wrap’, you’ll want to replace this with your header wrapper selector or whatever selector you have that you want to fix to the top of the viewport. This is storing the selector as a variable called “$top”.

Next you’ll see a function that detects scroll events on the browser window.

$(window).scroll(function(){

Then the fun stuff…

if($(document).scrollTop() > 200) {
    // if so, add the fixed class
    $top.addClass('fixed');
} else {
    // otherwise remove it
    $top.removeClass('fixed');
}

This code basically tells your viewport “Hey, when I scroll down greater than 200px, I want to do something.” In this case, we are adding a class to the previously referenced variable called “$top”.

The fun part of this is that you can also remove the class by using an else statement, which you can see above.

Feel free to adjust the ‘200’ to whatever you’d like it to be. Or if you’re really brave, you can use the script that I posted about viewport size to calculate the size of your first div, and make the menu stick after you’ve scrolled that distance. Just like my homepage does. 🙂

Now, in your stylesheet, you’ll need to add some style to the selector that you’re fixing to the top. Pretty simple. Something like this..

.navigation-wrap.fixed {
    position:fixed;
}

Hope this helps someone!