Have a div cling to top of screen if scrolled down past it

JavascriptHtmlCss

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

There was a https://stackoverflow.com/questions/2905908/horizontally-centering-an-absolute-position-to-match-a-relative-position">previous question today (no answers) that gave a http://perldoc.perl.org/perl.html">good example of this functionality. You can check the http://perldoc.perl.org/static/combined-20100403.js">relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:

  1. Page loads and element is position: static
  2. On scroll, the position is measured, and if the element is position: static and it's off the page then the element is flipped to position: fixed.

I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.

Solution 4 - Javascript

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.

<div style="position:fixed;top:0;left:0;right:0;height:100px;">Some buttons</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavascriptadamJLevView Answer on Stackoverflow
Solution 2 - JavascriptRafvsView Answer on Stackoverflow
Solution 3 - JavascriptAndrewView Answer on Stackoverflow
Solution 4 - JavascriptMitch DempseyView Answer on Stackoverflow