Facebook Style Scroll Fixed Header in JQuery

While doing some UI changes of a website, we had to implement a FIX header which remains fix on top of screen while scrolling. Facebook has a similar header which remains on top of content.

Now for this, there are number of jQuery plugins available out there! But in our case we weren’t allowed to add any new plugins to the technology stack of application (I know it sucks :-(). So here is a small JQuery based solution to make a DIV of header fixed on top of the screen while scrolling.

Related: Mouse Scroll Events in JQuery

The HTML

Below is the HTML code. It contain a simple div #header which we want to freeze at the top. Note that we have included JQuery directly from jquery.com site (In my application we have included older version of jquery from out tech stack).

<HTML> <HEAD> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <title>Scroll Fixed Header like Facebook in JQuery - viralpatel.net</title> </HEAD> <BODY> <div id="header"> <h1>Scroll Fix Header like Facebook in JQuery</h1> </div> <p>Some dumb text to add scrolling in page <br/><br/><br/><br/><br/></p> <p>Some more dumb text to add scrolling in page <br/><br/><br/><br/><br/></p> <p>Some more dumb text to add scrolling in page <br/><br/><br/><br/><br/></p> <p>Some more dumb text to add scrolling in page <br/><br/><br/><br/><br/></p> </BODY> </HTML>
Code language: HTML, XML (xml)

In above HTML, we added few lines “Some dumb text to add…” just to make page scrollable.

The JQuery

The JQuery code is pretty straight forward. Take a look:

<SCRIPT> $(document).ready(function() { var div = $('#header'); var start = $(div).offset().top; $.event.add(window, "scroll", function() { var p = $(window).scrollTop(); $(div).css('position',((p)>start) ? 'fixed' : 'static'); $(div).css('top',((p)>start) ? '0px' : ''); }); }); </SCRIPT>
Code language: HTML, XML (xml)

We have added an event listener to “scroll” event. This handler function gets called each time scroll event is fired in browser.

Now we select the header element (highlighted in above code) and simply do some position stuff. We make the header div’s position fixed of static depending upon the state of scroll position. Also the top attribute is set to 0px in case we want to make it fix, when page is scrolled down.

Online Demo

Demo

Download

Get our Articles via Email. Enter your email address.

You may also like...

49 Comments

  1. hh says:

    hi, i looked your demo page using chrome 16.
    if you scroll slowly enough like one step per scroll, header disappears then with next scroll it shown. and you cant scroll to the end of screen to see copyright section, js code moves page one scroll step up.
    so i think this mini plugin is not eligible to use.

    • @hh: Opps, well catch :)
      I fixed this issue and updated the tutorial. Thanks for the feedback.

  2. PHANI says:

    in IE8 its not working.

  3. Paras says:

    Please tell,
    How to run this?

  4. chris says:

    Very cool – I’ve put it on my site. Was wondering if you know of a way to make the header not “jump” during the initial scroll?

  5. Carol says:

    You could acheive the same by simply using #header{‘position:fixed’} in CSS.

    • andre says:

      agree using this “plugin” is simply waste of time and stupid
      or
      maybe what he means by “we weren’t allowed to add any new plugins to the technology stack of application” is css lol

    • no ! It’s different things.

    • devhaa says:

      Nope, you cannot achieve the same results with CSS. You can make it work with CSS only if the content that needs to be fixed is at the top of the page already; otherwise it will mess up your layout.

  6. ravi says:

    not able to see demo in FF11

  7. john says:

    why not use css??

  8. Thank you for this!

    Here’s a more generic implementation. I made this in thecontext of Drupal, so am using a readily available object there for a storage bin, but this same technique should be easy to implement using other locations for storage:

    function setup_sticky_elements() {
    
      Drupal.settings['_sticky'] = $('.sticky');
      $.each(Drupal.settings._sticky, function(s, sticky) {
        var start = (temp = $(this).attr('stickyat')) ? temp : 100;
        start -= 15; // don't know why this is needed, but somethig was bumping it by 15, sooo...
        start = $(sticky).offset().top - start;
        $(sticky).data({
          'sticky': {
            'start': start
          }
        });
      });
    
      $.event.add(window, 'scroll', function() {
          $.each(Drupal.settings._sticky, function(s, sticky) {
            var data = $(sticky).data('sticky');
            var p = $(window).scrollTop();
            var css = {};
            if (p &gt; data.start) {
              css['position'] = 'fixed';
              css['top'] = '100px';
            } else {
              css['position'] = 'static';
              css['top'] = '0px';
            }
            $(sticky).css(css);
          });
      });
      
    }
    

  9. Jibin says:

    The demo button is not working

    • @Jibin – Thanks for pointing this out. Seems the demo file is accedently deleted. I ll fix this right away.

  10. ben says:

    my header div increases its width by around 20% to the right upon scrolling the first time on FF12.0 and ie9. why is this and how do i keep the original size intact?

  11. salvatore says:

    What about using jquery cookies for implementing closing windows (like close this forever)? Could be useful for the most of visitors!

  12. Klick_arie says:

    I will try this,,, hehehe thank’s for share

  13. Chirag Gurjar says:

    Hi,

    I am trying to implement this fixed header with 80% width but does not keep 80% width through out it is increased automatically to 100%. can you let me know ? why ?

    Thanks,
    Chirag

  14. Eeshan Ag says:

    Hi there, I was wondering if you could help me out with the code for how you’ve done your current websites header. Just like the positioning on your header changes from static to fixed, how can I implement the same for my website.? Thank you.

  15. sonu patel says:

    hi
    i tried the above code but the header didnot remained fixed and moved and also there was gap between the top and left margin…

    please help

  16. sonu patel says:

    hello once again,
    i was implementing these codes visual studio 10 in ASP.NET…
    however when i tried to do in normal html file the header was fixed but there were marginal gap between the four sides of header…
    please help

  17. sonu patel says:

    sorry for the trouble ….i have corrected it..

    great help with the code
    Thank you once again

  18. Samarth Chawla says:

    Y U NO use CSS?

  19. MarcK says:

    Why not just use css { position:fixed }? Has the same effect with less code and does not blink.

  20. not working in IE9, kindly help.

  21. siddhartha says:

    You have done great Job dear. I have done this with jqxgrid. I have asked to their support team they told me this is not possible but i tried your example with little modification with z index and visiblity css and i have achieve this. my modification is like this:

    $(document).ready(function () {
                	var $elem = $('.jqx-grid-header'); // Original element with attached data
                    var start = $elem.offset().top;
                    $(window).scroll(function(){
                        var p = $(window).scrollTop();
                        $elem.css('position',((p)&gt;start) ? 'fixed' : 'static');
                        $elem.css('top',((p)&gt;start) ? '0px' : '');
                        $elem.css('z-index','10000');
                        $elem.css('visibility','block');
                    }); 
    });
    

  22. Miomir says:

    Here i have problem, when i have inside body some fixed element, when i scroll header goes over it?

  23. Mohamed says:

    Hello Dear….

    plz. help me

    is exmple very good..

    i want make padding if start fiexd div after scrollbar >>

    note: i want padding from bottom this div fiexd >>>

  24. Its nice to know but use css. It’s so simple and so easy to learn. Thanks for sharing all views…

  25. Arvind says:

    this header does not remain fixed in IE 8 and IE 9. Any one could help?

  26. Hung says:

    not working in IE9

  27. szed says:

    Not working on IE9…
    Anyone ?

  28. HifzurRahman says:

    good job,this blog helps me a lot..thanx

  29. Raza says:

    Hi,
    Your code isn’t running when Header div is used in side AJAX Update Panel. Any solution?

  30. hello there. As I can see you are using WordPress theme. I just want a header something like on your website… A header which will stick to top of the page after scrolling a bit.. please help

    As I am not a techie. just a beginner. would love if you can provide the full codes to make this happen. thanks in advance!

  31. Mayank says:

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

  32. pratiksha says:

    this code is not workin in IE9 nor is the scroll with mouse working

  33. coool article i m happy

  34. robbin says:

    Thanks for your code.

    I found there is an problem when scroll near the fixed-bar, a small shake, because when you set the fixed-bar fixed, and then the body html will be shorter than before, so I fixed this problem and share here.

    var div = $('#header');
    if(div.size()) {
        var placehoder  = $('<div>').hide();
        div.after(placehoder);
        
        var start = $(div).offset().top;
        $.event.add(window, "scroll", function() {
            var p = $(window).scrollTop();
            //console.log(start,p);
            if (p > start) {
              placehoder.height(div.height()).show();
            } else {
              placehoder.hide();
            }
            $(div).css('position',((p)>start) ? 'fixed' : 'static');
            $(div).css('top',((p)>start) ? '0px' : '');
        });
      }
    

  35. Rahat says:

    Hello.

    My Header is centralized. like:

    #header {
    	height: 90px;
    	width: 1000px;
    	margin-top: 0px;
    	margin-right: auto;
    	margin-left: auto;
    	background-color:white;
    }
    
    

    So problem is: When i scrolling page my header is aligning to left side of window. How can i fix this problem?
    Thanks.

    • @Rahat

      Why not try out

      #header {
          height: 90px;
          width: 1000px;
          position: fixed;
          top: 0;
          left: 50%;
          margin-left: -500px;
          background-color:white;
      }
      


      This will keep the header centered while having the header stay at the top. Then in jQuery you can have it check for the position of the scroll and if you like make the header fade out after a certain position.

      I did something similar but it is kind of the opposite. I didn’t want a logo to appear until it past a certain point of the scrollbar.

  36. Jiten says:

    Hi Viral..
    I have a page with header,footer, left panel and main content in for part as following

    <table style="width: 100%;" border="1">
    	<tr style="height: 20%;">
    		<td colspan="2"><div id="header-div" style="width: 100%;"></div></td>
    	</tr>
    	<tr style="height: 60%;">
    		<td style="width: 13%;" valign="top"><div id="sidebar-div" style="width: 100%;margin-top: 1px;top: 1px;"></div></td>
    		<td style="width: 87%;"><div id="mainContent-div" style="width: 100%;"></div></td>
    	</tr>
    	<tr style="height: 20%;">
    		<td colspan="2"><div id="footer-div" style="width: 100%;"></div></td>
    	</tr>
    </table>
    

    I want to fix header footer and left panel. only main content is not fixed and scrollable.

    I dont have depth knowledge on script side.

    Can you please help to do same..

    Thanks in advance… :)

    • Why not set your mainContent-div to “overflow:auto” and the rest of the divs to “position:fixed”

      And instead of using tables it can be set up like:

      <!DOCTYPE HTML>
      <html>
      <head>
      <meta charset=utf-8">
      <title>Untitled Document</title>
      <style type="text/css">
      body {
      	margin: 0;
      	padding: 0;
          width:100%;
          height:100%;
      }
      #container {
      	width:100%;
      	background:#FFF;
      }
      #header {
      	width:100%;
          height:20%;
          position:fixed;
      }
      #sidebar {
      	width:13%;
          height:60%;
          position:fixed;
          top: 20%;
          left:0;
      }
      #content {
      	width: 87%;
          height: 60%;
      	position:fixed;
          overflow:auto;
          top:20%;
          right:0;
      }
      #footer {
      	width:100%;
          height:20%;
      	position:fixed;
          left:0;
          bottom:0;
          }
      </style>
      </head>
      <body>
      <div id="container">
          <div id="header"></div><!-- end #header -->
          <div id="sidebar"></div><!-- end #sidebar -->
          <div id="content"></div><!-- end #content -->
          <div id="footer"></div><!-- end .footer -->
      </div><!-- end .container -->
      </body>
      </html>
      

  37. Rahmat says:

    Very helpful. Thanks…

  38. shah says:

    interesting article working fine, thanks for sharing

  39. Apni PSP says:

    Informative Post

  40. expertx says:

    Thank you very much for providing us such a great Post.

  41. Rohit says:

    Hello,

    Well explained without confusion. Keep sharing thanks.”
    “Well, explained and informative. Really this blog is helpful to me.

  42. Amazing Blog Thank you for sharing

Leave a Reply

Your email address will not be published. Required fields are marked *