Make a div stick to top when scrolled to

There are times when you would want to display a bar at the top of the page when user scrolls on the page and it should go back to its original position when the user scrolls back up. This is particularly useful when you want to add say a share bar, a search bar, etc and make it always visible even when the user is at the bottom of the page.


In my example I would be displaying a bar after a paragraph of text, and when the user scroll below that, the bar will stick to the top and have different CSS. When the user scrolls back to the top the bar will go back to its original position and the CSS will be changed.

By using jQuery, CSS and some HTML we can easily implement this. Below are the code snippets that would be required to implement this.

jQuery code:

// This function will be executed when the user scrolls the page.
$(window).scroll(function(e) {
    // Get the position of the location where the scroller starts.
    var scroller_anchor = $(".scroller_anchor").offset().top;
    
    // Check if the user has scrolled and the current position is after the scroller start location and if its not already fixed at the top 
    if ($(this).scrollTop() >= scroller_anchor && $('.scroller').css('position') != 'fixed') 
    {    // Change the CSS of the scroller to hilight it and fix it at the top of the screen.
        $('.scroller').css({
            'background': '#CCC',
            'border': '1px solid #000',
            'position': 'fixed',
            'top': '0px'
        });
        // Changing the height of the scroller anchor to that of scroller so that there is no change in the overall height of the page.
        $('.scroller_anchor').css('height', '50px');
    } 
    else if ($(this).scrollTop() < scroller_anchor && $('.scroller').css('position') != 'relative') 
    {    // If the user has scrolled back to the location above the scroller anchor place it back into the content.
        
        // Change the height of the scroller anchor to 0 and now we will be adding the scroller back to the content.
        $('.scroller_anchor').css('height', '0px');
        
        // Change the CSS and put it back to its original position.
        $('.scroller').css({
            'background': '#FFF',
            'border': '1px solid #CCC',
            'position': 'relative'
        });
    }
});

HTML Code:

<div class="container">
    <div class="test_content">
		Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum metus nec neque convallis id interdum nibh aliquet. Nulla eget varius diam. Ut ut dolor dolor. Mauris vehicula sodales mi quis euismod. In sem metus, volutpat nec fringilla sed, fermentum ac turpis. Cras aliquam venenatis rutrum. Donec pharetra ante sit amet justo pellentesque nec consequat ante elementum. Ut imperdiet iaculis tortor, id pretium urna pharetra sit amet. Aenean pharetra nunc risus, ac scelerisque urna. Morbi dictum egestas augue, in euismod metus commodo ac. Duis nisl ante, consequat et tincidunt id, eleifend eu ante. Integer lectus velit, tempus eu feugiat et, adipiscing ut mauris.
    </div>
    
    <!-- This div is used to indicate the original position of the scrollable fixed div. -->
    <div class="scroller_anchor"></div>
    
    <!-- This div will be displayed as fixed bar at the top of the page, when user scrolls -->
    <div class="scroller">This is the scrollable bar</div>
    
    <div class="test_content">
        Quisque sollicitudin elit vitae diam consequat accumsan. Suspendisse potenti. Donec dapibus tortor at justo eleifend at pellentesque leo lobortis. Etiam ultrices leo et nulla iaculis eu facilisis augue fermentum. Pellentesque eu leo purus. Vestibulum bibendum, metus at bibendum blandit, lacus neque porttitor diam, id facilisis lectus mauris et leo. Donec adipiscing interdum lacus sed condimentum. In auctor sollicitudin orci, ac interdum risus aliquet ullamcorper. Curabitur mollis accumsan vulputate. Etiam adipiscing diam nec dui posuere ut tincidunt felis tristique. Vestibulum neque enim, placerat sed placerat commodo, consectetur ac mauris. Sed ultrices pretium nibh, a blandit libero imperdiet pulvinar. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
    </div>
    ...
</div>

CSS Code:

.container{font-size:14px; margin:0 auto; width:960px}
.test_content{margin:10px 0;}
.scroller_anchor{height:0px; margin:0; padding:0;}
.scroller{background:#FFF; border:1px solid #CCC; margin:0 0 10px; z-index:100; height:50px; font-size:18px; font-weight:bold; text-align:center; width:960px;}
Here are the links to code (in jsFiddle) and demo.
Code
Demo

I have tested this on following browsers/systems

  • Internet Explorer 9 on Windows 7 Professional(64 bit)
  • Internet Explorer 8 on Windows XP Professional
  • Firefox 8.0.1 on Windows 7 Professional(64 bit) and Windows XP Professional
  • Chrome 16 on Windows 7 Professional(64 bit) and Windows XP Professional
  • Opera 11.50 on Windows XP Professional
  • Safari 5.0.3 on Windows XP Professional
I have modified code of some answers from Stackoverflow question to work so that when the user scrolls below the bar’s original position the bar will stick to the top of the screen with changed CSS and when the user scrolls back up, the bar goes back to its original position and the CSS is changed back.
Note: I do not take responsibility for proper functioning of the above mentioned steps under all circumstances. I am not responsible for any damages to your computer, website, blog, application or any thing else.
  1. Great post.. thanks for the tip, it inspires me to develop this technique further to create a floating social bar

  2. I tried to change width:960px with width:100% to have a fluid layout, but it seems to not work correctly…why?

    anyway, great article, indeed! it works, as it is, in all major browsers! Well done Virendra!

    • Hi Olympic12,
      Can you tell me what were you changing? Did you change only the width of the scroller? It is contained withing another div with class “container” which also has a width of 960px. This is probably the reason it didn’t work. Let me know if it does not work.

  3. Hi Virendra, thanks for a nice snippet of useful code! I’m wondering if you could make this iPad compatible too? It doesn’t seem to register the window scroll.

  4. wow brilliant nice work i really appreciate this. keep it up.

  5. Hi, Its working gr8… but the jquery is conflicting with another stuff…. ?
    how to make this happen with out conflicting to other jquery… any help ?

  6. Thanks for the great article. I’ve been looking for a way to do this and this really came in handy. I’ve signed up to receive notices via email when you post to your blog. You’ve got a lot of helpful information here. Thanks again!!

  7. Thanks a lot for the snippet.
    works great and easy to implement.

  8. Thanks for article !
    It was usefull for me

  9. It don’t work well on mobile. eg: IPhone safari

    • What is the problem that you are having? I had tested this only on desktop in the browsers that I had mentioned in the post. However, it seems to work fine on iphone too, but I did notice that on safari on iphone the div takes a little time to stick, until the window stops scrolling.

  10. Thanks a lot for this, I have been searching for this for a long time, awesome article and working great.

  11. When changing the class names in fiddle it works fine. When I make the changes and implement it in my site and check it it doesnot work.
    I made a sepaerate .js file but looking in firebug it does not show up as been red. I have not uploaded it could the flaw be in that?
    How should I get this done wright all help appreciated.

    thx,
    Mike

    The Netherlands

  12. This is a Great job , Thanks

  13. where do I put the jguery code? I don’t understand that part.

Leave a Reply