tags:

views:

45

answers:

2
+2  Q: 

Fixed Position CSS

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?

+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
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
Works for me, Robert. (I just added an edit for IE compatibility.)
Andrew Vit
It works when you scroll down, but when you scroll back up it sticks until you hit the top of the window.
Robert
Got it, thanks: I didn't even notice that. :) I guess this answer is the same as yours now, except without jQuery...
Andrew Vit
+3  A: 
  1. On page load create a variable containing the default top offset of the menu.
  2. Monitor the scroll event, if scrollTop > that original top offset, make the position fixed, otherwise static.
  3. Profit.

Example

http://jsfiddle.net/49gPT/

Robert