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

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
<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:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
<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.

Online Demo


--
Wasim Akhtar




--
Wasim Akhtar

No comments:

Post a Comment

If you have any question please let me know

[Software Update] Microsoft Edge 123.0.2420.65 Stable Released, Here is What’s New and Fixed

UPDATE: Release of Microsoft Edge 123.0.2420.65 stable version. Good news for Microsoft Edge users! Microsoft has released Chromium-based Mi...