On my website, I have a div beneath my header with some quick links. I am using http://davidwalsh.name/persistent-header-opacity to keep that div on-screen at all times. However, I want it to show at the top (position:fixed;top:0px;
, but only once the original place has been passed. In other words, I don't want it sticking to the top until the user has scrolled past it. How?
views:
45answers:
2
+1
A:
You can do this using JavaScript by listening for the scroll event and responding with a style change based on the scroll position:
var nav = document.getElementById('hmenus');
var navTop = nav.offsetTop;
window.onscroll = function(e) {
var scrollY = window.scrollY ? window.scrollY : document.documentElement.scrollTop;
if (navTop < scrollY) {
nav.style.position = 'fixed'; nav.style.top = 0;
} else {
nav.style.position = ""; nav.style.top = "";
}
}
#hmenus
is a stackoverflow element, so you can try it right here in Firebug. :-)
Andrew Vit
2010-09-17 23:58:16
You'll want to capture the default offset outside of the if statement, otherwise, if you set its position to fixed with a top of 0, it will continually be comparing 0 to the scroll position.
Robert
2010-09-18 00:01:01
Works for me, Robert. (I just added an edit for IE compatibility.)
Andrew Vit
2010-09-18 00:15:31
It works when you scroll down, but when you scroll back up it sticks until you hit the top of the window.
Robert
2010-09-18 00:25:14
Got it, thanks: I didn't even notice that. :) I guess this answer is the same as yours now, except without jQuery...
Andrew Vit
2010-09-18 01:13:20
+3
A:
- On page load create a variable containing the default top offset of the menu.
- Monitor the scroll event, if scrollTop > that original top offset, make the position fixed, otherwise static.
- Profit.
Example
Robert
2010-09-17 23:58:46