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

View Comments

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

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

    • 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

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

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

    [code language="js"]
    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);
    });
    });

    }
    [/code]

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

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

Share
Published by
Viral Patel
Tags: facebook header JQuery JQuery Events mouse scroll event

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago