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>

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>

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




37 Comments

  • hh 11 January, 2012, 18:49

    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.

    • Viral Patel 11 January, 2012, 21:25

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

  • PHANI 12 January, 2012, 4:23

    in IE8 its not working.

  • Paras 13 January, 2012, 15:31

    Please tell,
    How to run this?

  • chris 19 January, 2012, 23:48

    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?

  • Carol 2 February, 2012, 21:54

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

    • andre 8 February, 2012, 22:32

      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

    • manoj kumar 17 November, 2012, 19:17

      no ! It’s different things.

  • ravi 21 February, 2012, 13:23

    not able to see demo in FF11

  • john 19 March, 2012, 19:32

    why not use css??

  • Sean P. O. MacCath-Moran 24 April, 2012, 23:11

    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);
          });
      });
      
    }
    
  • Jibin 12 May, 2012, 23:10

    The demo button is not working

    • Viral Patel 12 May, 2012, 23:38

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

  • ben 30 May, 2012, 14:56

    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?

  • salvatore 10 June, 2012, 14:05

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

  • Klick_arie 25 June, 2012, 7:46

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

  • Chirag Gurjar 27 June, 2012, 11:38

    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

  • Eeshan Ag 28 June, 2012, 13:17

    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.

  • sonu patel 4 July, 2012, 8:45

    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

  • sonu patel 4 July, 2012, 9:08

    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

  • sonu patel 4 July, 2012, 9:18

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

    great help with the code
    Thank you once again

  • Samarth Chawla 17 July, 2012, 19:03

    Y U NO use CSS?

  • MarcK 8 September, 2012, 10:47

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

  • Osama Mursleen 19 September, 2012, 12:04

    not working in IE9, kindly help.

  • siddhartha 3 October, 2012, 17:44

    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');
                    }); 
    });
    
  • Miomir 13 October, 2012, 3:17

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

  • Mohamed 13 October, 2012, 20:26

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

  • Dhananay Kumar 16 October, 2012, 16:25

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

  • Arvind 17 October, 2012, 18:22

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

  • Hung 27 October, 2012, 18:03

    not working in IE9

  • szed 31 October, 2012, 13:38

    Not working on IE9…
    Anyone ?

  • HifzurRahman 9 November, 2012, 10:10

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

  • Raza 29 November, 2012, 19:24

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

  • Kamal Singh 31 January, 2013, 4:13

    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!

  • Mayank 7 February, 2013, 9:43

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

  • pratiksha 25 March, 2013, 11:47

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

  • future multimedia 23 April, 2013, 11:00

    coool article i m happy

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]