Griffiths web design based in Royston, Hertfordshire, United Kingdom


Hide header on scroll down and show on scroll up - using jQuery

Author:   Michael Griffiths

Date created:   13 July 2016

[l] Fixed headers are everywhere you look these days, for example; Facebook uses a fixed header as do thousands (if not millions) of other sites. It’s a wonderful thing and, if used correctly, can massively enhance the user’s experience of your site. However there are cases where it is just plain annoying and gets in the way. One site I visited recently, which shall go unnamed, had a beautiful background image of a lovely yellow orchid on the header which is permanently stuck to the top of the screen. On the desktop this was not an issue but on the mobile it took up quite a bit of valuable on page real estate and made the content difficult to view and really appreciate.[/l] [l]In light of this I have decided to share with my wonderful readers a technique that expands on the idea of a fixed header. What we will try to achieve is to hide the header on scroll down and reveal it on scroll up. To do this we will be using a combination of HTML, CSS (css transitions is where the real magic will be performed) and JavaScript (specifically jQuery).[/l] [l]So our first step, assuming you have an html file already created, is to add in a reference to the jQuery library. We will do this just before the closing ‘body’ tag.[/l] [code] [/code] [l]Next we need to add some mark up. For this example all we need is a header, a div and a footer.[/l] [code]
[/code] [l]Note – Feel free to add some content into the elements we just created, in fact if you don’t you won’t be able to view the effect we are trying to create as there will be no content to scroll.[/l] [l]Next we need to add some css:[/l] [code] body { padding-top: 65px; /* same as header height; */ } header { background: #808080; color:#ffffff; height: 65px; position: fixed; top: 0; width: 100%; -o-transition: top 0.2s ease-in-out; -webkit-transition: top 0.2s ease-in-out; -moz-transition: top 0.2s ease-in-out; transition: top 0.2s ease-in-out; } .nav-up { top: -65px; /* same as header height */ } [/code] [l]First we added some padding to the top of the body, the same as the height of the header. This makes sure the content is not moved down by the header being displayed. Next we added some styles to the header. As you can see we have given the header a ‘height’ of ‘65px’ and a ‘width’ of ‘100%’ and also set its ‘position’ to ‘fixed’. We also set ‘top’ to ‘0’ so that it sticks to the top of the viewport. Next we set up the transition effects. As you can see there is 4 similar lines of css, the first three have vendor prefixes attached and the last one is the standard non-prefixed declaration of the style. You’ll notice that I have not included a vendor prefix to support internet explorer. That is because IE10+ has stable support for transition, earlier versions of IE however are about as capable as a paper umbrella in a monsoon.[/l] [l]We have also created a class called ‘nav-up’. This class sets the ‘top’ css property of the header to ‘-65px’, which is the same as the height of the header so I’m sure you guessed that this will hide the header from view. This class will be added and removed by JavaScript as required.[/l] [l]Now we can get on with the fun stuff, the JavaScript. Just a quick note before we start the JavaScript – attaching functions to the scroll event can have a horrendous impact on your site performance. To combat this we will be if the user has scrolled on an interval of 250 milliseconds rather than executing our code for each pixel has been scrolled.[/l] [l]If you are adding the script directly into your HTML page then add it in just before the closing ‘body’ tag but after the jQuery reference. If instead of writing it on the HTML page you are adding it into an external JavaScript file then add reference to that file in the same place (before the closing ‘body’ tag but after the jQuery reference). So our first bit of JavaScript will be to create a variable called ‘doneScroll’, you may name your variable what ever you wish but whatever you call it remember the name. This variable will hold a Boolean value (true or false) this will be used to tell our code whether the user has scrolled or not.[/l] [code] var doneScroll;[/code] [l]Now we have created our variable to hold our Boolean value we need to assign it a value. To do this we need to listen for the scroll event and then once the event has fired we need to add our value.[/l] [code] $(window).scroll(function (event) { doneScroll = true; });[/code] [l]After this an interval checks every 250 milliseconds to see if the value of ‘doneScroll’ has changed. If so it runs our function, ‘hasScrolled()’, then resets the value of ‘doneScroll’ back to false. Leave the contents of the function ‘hasScrolled’ empty for the time being, we will get to that in a moment. Your code should look something like the following:[/l] [code] setInterval(function () { if (doneScroll) { haveScrolled(); doneScroll = false; } }, 250); function haveScrolled() { } [/code] [l]Now we need to add the guts into our function, ‘haveScroilled’. But before we do that we need to add some more variables to the top of our script, underneath our ‘doneScroll’ variable.[/l] [code] var lastScrollTop = 0; var delta = 5; var navbarHeight = $('header').outerHeight(); [/code] [l]Inside our function ‘havescrolled’ we need to add some code to store our scroll position in a variable. We also need to check if the user has scrolled more than delta.[/l] [code] var st = $(this).scrollTop(); if (Math.abs(lastScrollTop - st) <= delta) return; [/code] [l]Now we need to check if the user has scrolled past the header and which direction they have scrolled in.[/l] [code]if (st > lastScrollTop && st > navbarHeight){ // Scroll Down $('header').removeClass('nav-down').addClass('nav-up'); } else { // Scroll Up // If did not scroll past the document (possible on mac)... if(st + $(window).height() < $(document).height()) { $('header').removeClass('nav-up').addClass('nav-down'); } } [/code] [l]And finally we need to set ‘lastScrollTop’ to the current position, as follows.[/l] [code] lastScrollTop = st; [/code] [l]That is all there is to it, I know easy wasn’t it? Below you will see the complete JavaScript, in case you want to compare yours to mine.[/l] [code] [/code] [l]Try running your page in a web browser and hopefully you will be pleased with the result. If you have any problems with the code then please let me know and I will be happy to help. If you found this article helpful or informative at all then I would really appreciate a share on the social media platform of your choice. Please pass it around so we can help as many people as possible. If you have any comments, queries, suggestions, complaints etc. then please let me know in the comments below or send me an email, [/l] [l]Good luck in all future endeavours, whether they be web development related or not :) [/l]

About the author

My name is Michael Griffiths, I am a website designer and developer and the owner of Griffiths Web Design. I am based in Royston, Hertfordshire. Most of my work is local, Hertfordshire, Cambridgeshire, Bedfordshire, Essex etc. but that’s not to say I won’t work elsewhere. One of the wonders of modern technology is remote working. So no matter where the client is located it is always possible to connect.

I specialise in creating ASP.NET webforms applications using C#. I use Microsoft SQL Server for database development and on the front end I use Html, CSS and JavaScript. I am also proficient in the use of jQuery and several CSS frameworks.

One of my greatest passions in life is learning. Which is why I chose to pursue a career in web design and development, technology is in a state of constant and rapid evolution which means there is always something new to learn. I also enjoy writing, both fiction and non-fiction.


Please feel free to leave a comment below:

James Smalls

Just what I was looking for, thanks

Michael Griffiths

No worries James. I'm glad it helped :)

Anna the iron developer

Thanks dude, really helped me

Michael Griffiths

No problem Anna the iron developer. Keep coming back to check for new posts

Anna the iron developer

I will!

Griffiths Web Design Logo by Michael Griffiths
Griffiths Web Design Logo by Michael Griffiths
Click to go to the top of the page