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.
            '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.
            '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.
    <!-- 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;

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 and demo.
View Demo
Download Source Code
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.

Related posts:

  1. Sticky Header and Footer using CSS
  2. Voting Functionality in a website
  3. 404 Error Page Best Practices
  4. Creating multiple virtual hosts/websites in Wampserver

31 thoughts on “Make a div stick to top when scrolled to”

  1. 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!

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

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

  3. 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 ?

  4. 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!!

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

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


    The Netherlands

  6. hi, i implemented this today and whilst i like the idea of the scroller_anchor, clever, the problem I’ve found is that it doesn’t work well if the scroller div is populated dynamically, i.e its height is not fixed. do you know if there is a work-around for this?

    1. hi, in fact I found the solution that works and maybe better for you to implement:
      instead of:
      $(‘.scroller_anchor’).css(‘height’, ’50px’);
      replace with:

  7. I really like the way the box sticks on top; but the demo page always shows 2 scroll bars, and even 3 when the browser window is made smaller after initial page load – definitely not a good User experience!

  8. hi, i keep getting this error on java console:
    TypeError: Not enough arguments to Window.scroll.

    and it does not work
    copyed your code into a joomla template…dunno why i get this
    have any clue ?

    here a link:

    check the div #nav .left1, that’s the one i’m trying to work with


  9. Hi Virendra,

    Great article, I’ve been searching around for this solution, and yours works beatifully. I got only one issue: I’m building this website:

    I’m using this effect on the header. I’ve renamed the classes scroller and scroller_anchor with topo and topo_fixo. Once I scroll down the website, it covers the title of the section right bellow the banner (faz e acontece). When I hit the anchor button for this section (agencia) on the menu, it scrolls down to the right position, but the header doesn’t appear, only after scrolling down. I’ve played around with it but couldn’t solve this. Any help would be much apreciated. Once again, great article.


Leave a Reply