I have a div which, when my page is first loaded, is about 100px from the top (it holds some buttons etc. for the page).
When a user scrolls past it, I would like the div to “follow” the user in that it attaches to the top of the screen. When the user returns to the top of the page, I want it back in its original position.
Visualization - xxxxx is the div:
Default (page load) User vertically scrolled well past it
--------- ---------
| | |xxxxxxx| < after div reaches top of screen when
|xxxxxxx| | | page is scrolled vertically, it stays
| | | | there
--------- ---------
The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.
This is done with something like this, attaching a handler to the window.scroll event
This simply adds a
stickyCSS class when the page has scrolled past it, and removes the class when it’s back up.And the CSS class looks like this
EDIT- Modified code to cache jQuery objects, faster now.