Scroll Activated Slide Down Header With jQuery
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:
1 2 3 4 5 |
<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:
1 2 3 4 5 6 7 8 9 10 11 12 |
#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:
1 2 3 4 5 6 7 8 9 10 11 |
$(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. 😛
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.
74 Comments
Tyler
Well that was fast. 🙂 Nice tutorial Paul.
Paul Robinson
No problem. 😉 Glad you liked it.
Greg Babula
This was really useful man, thanks
Paul Robinson
Thanks. 🙂
dboz
thanks for this.. so simple..
Paul Robinson
Nice to know it was useful to you, and no problem. 🙂
Neil
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.
Paul Robinson
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. 😉
Giacomo
Very useful! I used your script to develop the behavior of the “comment box” in my blog, on the right side. thanks!
Paul Robinson
Glad it was helpful. 🙂
Rustan
Nice and Simple! Good work Paul! It really helps.
Paul Robinson
No worries. 😉
Alex
Seems a bit buggy, the height of the bar gets clipped as you scroll up and down each time, eventually not revealing at all…
Paul Robinson
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.
Paul Robinson
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.
bluepicaso
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
Paul Robinson
No worries Bluepicaso. Glad I was able to help you out.
Nice site by the way. 🙂
kathy
yet again you manage to have exactly what i am looking for. was just trying to emulate the Apture bar.
Paul Robinson
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. 🙂
kathy
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.
Paul Robinson
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.
kathy
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
[code]
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);
}
});
});
[/code]
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.
Paul Robinson
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.
Paul Robinson
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?
kathy
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)
Paul Robinson
Ahh, thank god. 🙂
Let me know if you need any other help, always happy to help out. 😉
Chase Adams
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. 🙂
Paul Robinson
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).
Chase Adams
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.
Paul Robinson
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. 🙁
Bob
awesome!
Paul Robinson
Thank you Bob. 🙂
seth
That’s what i’ve been searching for. Great tutorial, thanks…
Paul Robinson
No problem Seth. Glad it was helpful & thanks for reading. 🙂
Rahul R
I was looking for this one for a long time. Thanks bro.
But what about ie6. Seems like having some problem?
Paul Robinson
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. 😉
Pedro Lopes
is there a way to achieve this but from the bottom instead of top ?
Paul Robinson
Hi Pedro,
I haven’t tried it, but it should be as simple as replacing all references in CSS & JS of ‘top’ to ‘bottom’. 😉
Patrick
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 🙂
Paul Robinson
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:
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.
Patrick
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.
Paul Robinson
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.
Paul Robinson
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:
With easing 1.3 and the easing compatibility file.
Mike
Hi Paul,
I am creating my website with weebly. I did it like you explained in your post, but the header is not sliding down. The jQuery is not working. Is it possible to make it work with weebly. Please help!
Paul Robinson
Hi Mike,
I honestly don’t have a clue as I’ve never used Weebly before. You best bet would be to try some basic JS commands & see if they execute, if they do there may be a problem on the page somewhere.
Try a command like:
If you see it then Javascript is working. If you don’t then Weebly probably won’t allow you to use it. Also don’t forget to attach jQuery to the head of your weebly site. Try attaching it from the Google CDN.
Dan
I think you should include some (albeit ugly) booleans to prevent the .stop().animate() being called continuously when you scroll.. otherwise you’ll find if you scroll down fast enough, the animation is constantly stopped and restarted, and it doesn’t complete until you stop scrolling:
Paul Robinson
Hi Dan,
I did actually have booleans in when I originally created the tutorial. I think this one is down to preference. I prefer having
stop()
or if you likestop(true)
as it cancels the animation & starts the next one even if it is half way through.You can however use it the way you have, I believe you could probably use the
:not(:animated)
selector instead of the booleans, but I haven’t used it much so I’m not sure.Thanks for the comment. It’s interesting to see how preference can change the code slightly. 🙂
Dan
Tried out the not(:animated) method and it fails to trigger too often. I think the booleans are a little more robust.
Dan
Scratch that.. both have the same issue.
Dan
lol, sorry to spam your blog, but when I was switching versions I’d checked before it had uploaded.
To re-cap, the ugly boolean method works much more reliably than the not(:animated) thing.. try it out.
Paul Robinson
Hi Dan,
No worries. I’ve never noticed much difference between the two when using them before. However I haven’t had the time to try it on this example so I’ll take your word for it. 😉
Trashfunkel
SUPER USEFULL THANK! !!!!!!!!
Yearn
Thanks.
Chris
Very nice tutorial, I see this feature becoming very popular on well built websites.
Dante’
You have no idea how long I have been looking for this code, thank you.
Paul Robinson
Glad it helped Dante.
david g
can someone just help me with this. if i were to set this up on my blog. i have no idea how to do any of this coding.
Paul Robinson
Hi David,
If you need help setting this up I am available to hire. Just drop me an email using the Hire Me page.
Micheal
Hi Paul,
how can i change the speed of fading in and out?
Paul Robinson
Hi Micheal,
Do you mean the sliding up & down? This tutorial doesn’t have a fade in/out. Either way the number ‘500’ on the end of the ‘animate’ lines of the jQuery control the time in milliseconds.
Mona
Sorry to sound incredibly thick but where does the HTML and the JQuery go?
I’m using WordPress.org
Best,
Mona