Get Started!

Stick on Scroll

How to react to scrolling and apply a class when a given element start to scroll out of view.

Simple example

Given a page with an element that should scroll with the page, until it starts to scroll out of view. At which point it sticks to the top of the page and the rest of the content starts to scroll out of view.

The HTML

Here's the HTML of the element we want to make sticky:

<div id="alt_nav" role="navigation">
  <!-- My Nav Content !-->
</div>

The JavaScript

Whenever the page is rendered the following JavaScript is executed:

  var offset = $('#alt_nav').offset();

  $('body>form').on('scroll', function(e){

    if( $('body>form').scrollTop() > offset.top){
      $body.addClass('scrolled');
    } else {
      $body.removeClass('scrolled');          
    }
  });

This code measure the offset of the element; attaches to the scroll event of the body. When triggered we measure the scrolled distance via the scrollTop property of the body element (this). A class scrolled is either added or removed from the body element.

The CSS

@scrollTopHeight:56px;

body.scrolled {

  padding-top:@scrollTopHeight;

  #alt_nav[role="navigation"] {
    position:fixed;
    top:0;
    left:0;
    right:0;
    z-index:999;
  }

  header[role="banner"]{
    display:none;
  }

  [role="main"]{
    position:relative;
    top: 121px;
    padding-bottom:121px;
    padding-top:@line-height-computed;
  }

}

This assume you've used the Sticky footer css for the .net support with the following css :

html, body {
  overflow:hidden;

  & > form {
    overflow:auto;
  }
}