Facebook Style Scroll Fixed Header in JQuery
19
July
2013

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.

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

Website Development Company Vadodara

| Tags:
  • 1652 View
  • Pin It