Home > Tutorials > Javascript > Scroll Activated Slide Down Header With jQuery
Permalink to Scroll Activated Slide Down Header With jQuery

Scroll Activated Slide Down Header With jQuery

by on 04.09.2010 | 43 comments

I’m always looking for inspiration for new tutorials, and thanks to you lovely people I’ve always got something to try & create. Today I was asked to create a slide down header (similar to the footer), but with a creative twist.

Update: 17/08/2010

After a little bit of work I have fixed the bug that caused the header to break. I have changed the tutorial below to reflect the changes. Please read through it again if you have already used the code & change the necessary parts.

Yesterday via Twitter, I received a request for a tutorial. It was to make a slide down header, similar to that of the slide up footer I posted yesterday. However this one had a very interesting twist. Here is the tweet:

You should write a tutorial on how to make a sticky header, like here: http://www.scienceblog.com/cms/index.php

The header (bar thing) that scienceblog have is interesting because it doesn’t appear until you scroll a certain distance down the page. So let’s see if we can create something like it. As always my design abilities are shocking, but all the code is there & most importantly it works.

HTML

First let’s look at the HTML:

<div id="headerSlideContainer">
	<div id="headerSlideContent">
		Header content goes here!
	</div>
</div>

Heh. Not really anything to write home about is it. We have a container, this allows us to stretch the header to the full page width. Then we have a content container, this allows us to center our content in a smaller area while the header still stretches the full page width.

CSS

Now let’s take a look at the CSS:

#headerSlideContainer {
	position: fixed;
	top:-50px;
	width: 100%;
	background: black;
}
#headerSlideContent {
	width: 900px;
	height: 50px;
	margin: 0 auto;
	color: white;
}

Let’s have a look here. We set our container to be positioned fixed with a position set to the same as the height you plan to use for the content element but negative. So if your #headerSliderContent is 100px high you will need to set the position at -100px.

We set it’s width to 100% (the full page width). Also we set our background to black, feel free to go wild with that.

The content area is simple. We have a width of 900 pixels, a height of 50px and a margin to center it. You’ll probably want to customize all that though. The color is just so the text is visible on our black background. Again you’ll probably want to customize it.

jQuery

Onto the exciting part. The jQuery:

$(function() {
	var bar = $('#headerSlideContainer');
	var top = bar.css('top');
	$(window).scroll(function() {
		if($(this).scrollTop() > 50) {
			bar.stop().animate({'top' : '0px'}, 500);
		} else {
			bar.stop().animate({'top' : top}, 500);
		}
	});
});

Hold on to your hats people. First we open a standard on DOM ready. Next we tie a scroll event to the window. Why the window? Well we need to slide down our header if the page scrolls below a certain position, to do that we need to monitor the windows scroll position. Next, because it makes things quicker, we assign the jQuery object for our header container into a variable. We also store the current top position we set in the CSS earlier.

Now if this, which refers to the window, has a scroll position greater than 50 (feel free to customize), we tell the bar (our header) to animate the top position to 0px. Because our position is set to fixed 0px will always be the correct position to show the header fully. stop() tells jQuery not to queue animations so it becomes more responsive & doesn’t break if someone abuses it with lots of scrolling.

If our scroll position isn’t greater than 50 we need to hide the header. To do this we just animate the header back to it’s original position using the variable top we set earlier. The reason I have used a variable is so that you don’t have to edit the jQuery at all, you can if you like to change the scroll height & animation timings, but there is no need to. Just remember to set your negative top position in your CSS or it won’t work.

Example

I know you all like to see an example. It’s not very pretty, but like I said, I’m rubbish at design. I just do the coding. The design is up to you. :P

Done!

There we have it. A scroll activated sliding header. There is, of course, the problem that if your page isn’t high enough your scroll position will never pass the required number and as such the header will never show.

Let me know if you can think of any alternative actions to take should the page not scroll & I’ll add them on to the tutorial. As always, I hope you enjoyed this tutorial, if you have any questions or comments leave them below or drop me an email using the contact page.

Written by Paul Robinson

A Web coder in languages such as CSS, X/HTML, jQuery, but mostly PHP. Addicted to Girls Aloud, Jennifer Morrison, Carah Faye Charnow, TV Show Chuck, and completely in love with Yvonne Strahovski's smile.

Give something back!

If you LOVED this tutorial and would like to show your appreciation, please consider or a little something from our Amazon Wishlist.

Discussion: 43 Comments

  1. Apr 9th, 2010 @ 16:06:24

    Well that was fast. :) Nice tutorial Paul.


    • Apr 9th, 2010 @ 16:10:50

      No problem. ;) Glad you liked it.


  2. May 6th, 2010 @ 16:40:04

    This was really useful man, thanks


  3. May 8th, 2010 @ 23:30:46

    thanks for this.. so simple..


    • May 8th, 2010 @ 23:36:36

      Nice to know it was useful to you, and no problem. :)


  4. May 26th, 2010 @ 17:19:13

    Your tutorial is fantastic, but I have found the auto header slightly glitchy, if you play about with the scroll bar to much the slide down header stops working. Any help would be appreciated.

    Thanks again for a great looking and useable plug-in.

    Cheers.


    • May 26th, 2010 @ 17:54:53

      You know I did notice that a few days ago, but I’ve never been able to figure out what causes it.

      I’m going to have another look at it tonight so I’ll update the post, or post another comment if I find anything. ;)


  5. Jun 22nd, 2010 @ 21:21:27

    Very useful! I used your script to develop the behavior of the “comment box” in my blog, on the right side. thanks!


  6. Aug 4th, 2010 @ 08:36:17

    Nice and Simple! Good work Paul! It really helps.


  7. Aug 12th, 2010 @ 02:17:15

    Seems a bit buggy, the height of the bar gets clipped as you scroll up and down each time, eventually not revealing at all…


    • Aug 12th, 2010 @ 02:21:39

      Yeah, unfortunately it’s a bug I still haven’t managed to iron out. I’m going to take another crack at it in the next few days so I’ll update the post if I can sort it out.


    • Aug 17th, 2010 @ 17:40:33

      Just to let anyone following the comments via feed etc know. I have fixed the bug with the header getting clipped.

      There are some changes to both the CSS & jQuery in the post, please check them out if you want to fix that bug.


  8. Sep 25th, 2010 @ 19:37:00

    You just made my day.. Thanx a lot. i was previousy doin it on each specific click. I was using the same for “Go to top” option.
    Please visit http://www.TheCodingBox.com to see the application


    • Sep 25th, 2010 @ 22:22:29

      No worries Bluepicaso. Glad I was able to help you out.

      Nice site by the way. :)


  9. Feb 28th, 2011 @ 21:24:23

    yet again you manage to have exactly what i am looking for. was just trying to emulate the Apture bar.


    • Feb 28th, 2011 @ 22:10:54

      Glad I’ve been able to help you with what you were looking for once more. ;)

      If you every need something I don’t have feel free to request it. I’m always looking for ideas for new tutorials. :)


    • Mar 1st, 2011 @ 21:31:44

      your demo works in chrome, FF and IE, but I can’t make it work in WP across all 3…. copying your code directly too. only seems to work in Chrome. doesn’t slide in in IE and doesn’t slide out in FF. le sigh. will try again when I am fresher and hopefully report the reason why i am a moron.

      as far as new ideas- i am looking to ajaxify a theme. i’m about half way there…. have load pages and search. need a contact form and comments.


    • Mar 1st, 2011 @ 21:37:48

      Haha. AJAX and I aren’t speaking at the moment so that might be a difficult one, lol.

      As for the footer not working. Have you tried using the no conflict DOM ready function? That normally causes some strange problems for me.


    • Mar 1st, 2011 @ 21:49:04

      lol. i guess i can’t laugh that you and ajax aren’t speaking. we’re definitely on a break and I am rather constantly embattled with jquery… for the ‘write less, do more’ language…. we get into a lot of fights.

      i’ve modified the code w/ some alerts

      jQuery.noConflict();
      jQuery(document).ready(function($){
      		var bar = $('#headerSlideContainer');
      		var top = bar.css('top');
      		alert(top);
      		$(window).scroll(function() {
      			if($(this).scrollTop() > 50) {
      				bar.stop().animate({'top' : '0px'}, 500);
      				alert('yay');
      			} else {
      				bar.stop().animate({'top' : top}, 500);
      			}
      		});
      });
      

      and in FF the first alert isn’t negative, even though the top is definitely a negative value in CSS. off to a smashing start there. in IE the first alert shows the correct value (-110px) but then the next alert is never triggered.


    • Mar 1st, 2011 @ 22:05:33

      If you can give me maybe 20 – 25 minutes I’m gonna try throwing it into a WP theme myself to see what happens.

      Do you have Skype or anything? It might make it easier to work through the problem if you do.


    • Mar 1st, 2011 @ 22:17:28

      Just noticed I said footer earlier… I’ve no idea what I was talking about. Damn CSI distracting me, lol.

      I’ve just tried out the code on the basic Kubrick theme & it seems to work okay. The only problem is the new WP admin bar gets in the way if you are logged in.

      I’m not sure what could be causing the problem. Especially different symptoms in different browsers. Something in the theme conflicting? Is there any other jQuery code in your theme?


    • Mar 1st, 2011 @ 22:21:11

      Is there any other jQuery code in your theme?

      yes!! just commented out my other bit and it works as it should. now i just need get them to play nice. at least i know where to look (and that i am not a failure at cut and paste)


    • Mar 1st, 2011 @ 22:23:28

      Ahh, thank god. :)

      Let me know if you need any other help, always happy to help out. ;)


  10. Sep 13th, 2011 @ 13:39:20

    Hey Paul,

    Great tutorial!

    I have a few thoughts to consider though:

    Why not create your header div in such a way that there is the ‘visible’ styling and the scroll down header styling?

    One issue that usability enthusiasts would bring up is what happens if a user is using a screen reader, or styling & javascript are disabled?

    All of these issues could be eliminated by simply changing the class of the header, and setting the top to -50px or whatever your relative value is when the header scrolls out of sight.

    Alternatively, if your slide down header contains totally different content from your header, I would inject the headerSlideContainer with javascript, so if javascript is disabled, everything works just right.

    Degrading gracefully is what separates Web 2.0 from it’s predecessor. :)


    • Sep 13th, 2011 @ 14:23:46

      Hi Chase,

      Thanks for sharing your thoughts.

      I understand where you are coming from, but this isn’t really meant to replace your actual website header. If you did want that to be the case then I would highly recommend doing what you’ve said.

      I meant it to be more of a way to show an unobtrusive promo, or notification. I do agree however there should still be some way for it to be shown should JS be disabled.

      I think I’ll try to do another tutorial sometime soon taking graceful degradation into account. On a side note, if you are browsing with JS disabled these days you can kiss most of your favorite internet apps goodbye, but I still agree there should be some way for those without JS enabled to see the content (Screen readers, etc).


    • Sep 13th, 2011 @ 14:34:37

      Ah~ My apologies. I visited the link to the site that was referenced and it didn’t have the slide down header (maybe they’ve removed it?), so I made an assumption.

      In that case, it could easily degrade to just being shown at the bottom of the page, or above the wrapper, giving the wrapper a 50px margin (to offset for the header) should js be disabled.

      I like to add a ‘no-js’ class for degradation purposes that is removed on js being enabled.

      Either way, your site is great! I enjoyed perusing it this morning.


    • Sep 13th, 2011 @ 14:55:53

      No worries. I need to refresh the demo for this post, it’s from before the site was redesigned and doesn’t work very well any more.

      I love the ‘no-js’ class method it’s always been my favorite way of dealing with degradation.

      Thank you. Glad you’ve enjoyed looking around. I really need to post more often, but I run the site by myself & I’ve had a load of client based work so I’ve had no time to post much. :(


  11. Nov 10th, 2011 @ 14:35:13

    awesome!


  12. Nov 13th, 2011 @ 15:55:00

    That’s what i’ve been searching for. Great tutorial, thanks…


    • Nov 13th, 2011 @ 15:56:42

      No problem Seth. Glad it was helpful & thanks for reading. :)


  13. Nov 14th, 2011 @ 09:39:39

    I was looking for this one for a long time. Thanks bro.

    But what about ie6. Seems like having some problem?


    • Nov 14th, 2011 @ 10:59:45

      Hi Rahul,

      Personally I no longer support IE6 as it is a dead browser (or at least should be).

      The main problem is I don’t actually have anything to test in that will view as IE6 reliably. Most of those emulators never seem to work properly & the screenshot site’s don’t help when testing Javascript code such as this.

      What exactly is the problem in IE6 though & I’ll see if I can help out from memory. ;)


  14. Jan 10th, 2012 @ 03:01:40

    is there a way to achieve this but from the bottom instead of top ?


    • Jan 10th, 2012 @ 13:36:27

      Hi Pedro,

      I haven’t tried it, but it should be as simple as replacing all references in CSS & JS of ‘top’ to ‘bottom’. ;)


  15. Jan 15th, 2012 @ 10:50:55

    Hey there

    I’ve been looking for a version of the apture search bar to implement on my site and it looks like I’ve found a fantastic script, thanks very much for the tutorial. I just have one suggestion/request. I notice that you haven’t used the easing plugin for this script, which could possibly make the scroll-down appear a lot smoother. I’ve found this code on the jquery website:

    $( “p” ).animate({
    “opacity”: “show”
    }, { “duration”: “slow”, “easing”: “easein” });

    and I know the “easing” property has to be added somewhere to:

    bar.stop().animate({‘top’ : ’0px’}, 500);

    but I don’t know enough about javascript syntax yet to implement easing in. One great option I would use is the simple FadeIn easing effect, it really works well on this dropdown menu script I’ve been using:

    http://demos.99points.info/fancy_menus/

    Anyway, the script is fine without it and I will definitely be using it, I just think with easing enabled it could be even better.

    Cheers, bookmarked your site :)


    • Jan 15th, 2012 @ 13:56:13

      Hi Patrick,

      Well it’s deceptively simple to add in the easing. All you need to do is change the line you quoted from my code to this:

      bar.stop().animate({‘top’ : ’0px’}, {'duration': 500, 'easing': 'easein'});
      

      That should do it. Basically you replace where the duration is in the animate calls with an option list, including the duration you just removed & the new easing parameter.

      Hope that helps. Let me know if you need anything further.


    • Jan 17th, 2012 @ 08:52:15

      Hi Paul,

      Thanks for the reply, unfortunately I couldn’t get that to work. When I replaced the code the bar didn’t show at all, even though no syntax errors are showing and I’ve included in the document. I tried changing easein to easeIn but still didn’t get any luck.


    • Jan 17th, 2012 @ 12:25:30

      Hi Patrick,

      Hmm. That’s a little odd. I was going off memory, so I’ll actually try it out with easing & see if I can find out what’s going on for you.

      Check back soon & hopefully I’ll have an answer for you.


    • Jan 17th, 2012 @ 17:37:39

      Hey Patrick,

      A little later than I’d hoped thanks to work creeping up on me, but here is the code I ended up with & worked on my demo great:

      $(function() {
      		var bar = $('#headerSlideContainer');
      		var top = bar.css('top');
      		$(window).scroll(function() {
      			if($(this).scrollTop() > 50) {
      				bar.stop().animate({'top' : '0px'}, { 'duration' : 500, 'easing' : 'backinout' });
      			} else {
      				bar.stop().animate({'top' : top}, { 'duration' : 500, 'easing' : 'backinout' });
      			}
      		});
      	});
      

      With easing 1.3 and the easing compatibility file.


Leave a comment

Please enclose code in [lang] tags. For example [php] echo 'hello world'; [/php]

* Name, Email, Comment are Required