Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  32] [ 1]  / answers: 1 / hits: 135480  / 14 Years ago, tue, may 25, 2010, 12:00:00

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
--------- ---------

More From » html

 Answers
2

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



   // Cache selectors outside callback for performance. 
var $window = $(window),
$stickyEl = $('#the-sticky-div'),
elTop = $stickyEl.offset().top;

$window.scroll(function() {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});


This simply adds a sticky CSS class when the page has scrolled past it, and removes the class when it's back up.



And the CSS class looks like this



  #the-sticky-div.sticky {
position: fixed;
top: 0;
}


EDIT- Modified code to cache jQuery objects, faster now.


[#96687] Friday, May 21, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harrisonnelsonb

Total Points: 63
Total Questions: 112
Total Answers: 97

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;