So normally if you want to add a sticky header to a website you simply set the positioning for the element to be fixed right?
Done right? Thanks for dropping by!
Wait…you want to have a sticky header on a page where the header isn’t the first thing at the top of the site? Huh…you what?!? You want some random element in the middle of the page to stick to the top. Uh…that’s impossible. Okay enough with the soliloquy. Let’s do it.
The first thing you have to do is identify what you want to be “sticky” on scroll. Easy enough. For our tutorial we will be making the Genesis header sticky so we’ll be using the class .site-header. If you are using another theme you can simply take a look using the inspect element tool in Chrome (F12) and find the class or element that you want to target.
Next we need to fire up some jQuery to actually make this happen. What you were thinking we would do it with sorcery? Seriously though, jQuery is sorcery. Don’t tell anyone. It will ruin the fun.
Here is what we will be using:
Looks confusing right? It’s actually pretty simple. First we grab the header and then add the class .original to it. You’ll see why in a second. Next, we clone the header using .clone and insert it right after (in the same place) the original header using .insertAfter and then finally add a class of .clone to the newly created cloned header. Finally, some css tweaks to finish it off which basically stick the cloned the header to the top of the page removing .original class and hiding it. Pretty cool huh?
Next, we set the scrollIntervalID which will set how often the function runs…every 10ms.
Now for the actual code that makes it work. Most of the stuff here is to make sure that cloned element is an exact replica of the original so there are css values that are pulled and set. The real coding is the conditional statement that will return the cloned header if the page is scrolled past the “magic number” of pixels and of course if it’s not…we simply show the original header.
In order to find that “magic number” we have to use the .offset function. We set the variable orgElementPos to be the original header’s distance from the top of the page. We can then use this in our calculation to see if we should show the original header or the clone. Next our conditional…if the number of pixels scrolled i.e. $(window).scrollTop() is greater than or equal to the original header’s number of pixels away from the top…then we will see our clone. If not, we see the original. Essentially it’s the old switch-a-roo!
Honestly…the part that really seems like sorcery to me is that this all happens within a fraction of a millisecond while so many other things are happening in the browser as well. Amazing. I love the internet!
Hope this helps. I know it did for me when I was looking for a way to use a sticky header on a site with an advertisement banner stuck at the top above the header.