Saturday 14 July 2012

Facebook Style Scroll Fixed Header in JQuery


<HTML>
<HEAD>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <title>Scroll Fixed Header like Facebook in JQuery - pranaysonisoft.blogspot.com</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>



<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 topattribute is set to 0px in case we want to make it fix, when page is scrolled down.