So I’ve been tinkering lately with adding my own sticky-header functionality to the sites I develop for work. Most of the time templates we work with will have this feature built in, but sometimes they don’t. I’ve built a few sites in the last few weeks using a template that is solid at its core, but lacking in some of the more modern techniques, so enabling a sticky-header has been a manual process.

Luckily there is a really handy jQuery library that will assist in this quite nicely. It’s called classie.js and it is really cool. Classie.js is an awesome, super lightweight script that allows you to add, remove, toggle, and check for classes in the DOM very easily.

So what I’m doing to enable my sticky header is to add a class to the body tag after I have scrolled down the past the length of the header. I achieve this by delaring a variable that is equal to the height of the header. Instead of inputting a fixed height into my script variable I am using the .height(); method to get the height of my header and then using that to add a class to the body tag. Paste the code snippet below into the footer of your website (be sure to put it inside a <script> tag):

function init() {
window.addEventListener('scroll', function(e){
var distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = jQuery('#header').height(),
header = document.querySelector("body");
if (distanceY > shrinkOn) {
classie.add(header,"sticky-header");
} else {
if (classie.has(header,"sticky-header")) {
classie.remove(header,"sticky-header");
}
}
});
}
window.onload = init();

What this snippet does is dynamically get the height of the #header element and store that height as a variable called shrinkOn. We are also creating another variable called distanceY to track how far down the page we scroll. We compare the number stored in distanceY against shrinkOn, and if distanceY is more than shrinkOn classie.js adds the class sticky-header to the body tag. We can then use this class to stick the header to the top of the page. Paste the following into your stylesheet:

body.sticky-header div#main-nav {
position: fixed;
top: 0;
}

This will fix the #main-nav (which is presumably your main navigation container) to the top of the page once you scroll down the number of pixels equal to the height of the #header. You might also want to add some padding to the top of the #header equal to the header height so the page doesn’t jump up and down when sticky-header is added/removed from the body tag by classie.js. You can do that with some simple jQuery as well, but that is for a different tutorial.

So that’s about it! Try it out and let me know how it works for you in the comments below!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>