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 ---------                    --------- Just replace #sticky_div's_name_here with the name of your div, i.e. if your div was <div id="example"> you would put #example { position: sticky; top: 0; } .
Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.
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.
The trick to make infinity's answer work without the flickering is to put the scroll-check on another div then the one you want to have fixed.
Derived from the code viixii.com uses I ended up using this:
function sticky_relocate() {     var window_top = $(window).scrollTop();     var div_top = $('#sticky-anchor').offset().top;     if (window_top > div_top)         $('#sticky-element').addClass('sticky');     else         $('#sticky-element').removeClass('sticky'); }  $(function() {     $(window).scroll(sticky_relocate);     sticky_relocate(); }); This way the function is only called once the sticky-anchor is reached and thus won't be removing and adding the '.sticky' class on every scroll event.
Now it adds the sticky class when the sticky-anchor reaches the top and removes it once the sticky-anchor return into view.
Just place an empty div with a class acting like an anchor just above the element you want to have fixed.
Like so:
<div id="sticky-anchor"></div> <div id="sticky-element">Your sticky content</div> All credit for the code goes to viixii.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With