How to create a floating div on scroll with jQuery

Posted on by Chandan

We will create a floating div on scroll with jQuery with a straight forward approach. With the help of css position relative, absolute and fixed we will make the div float within a vertical space. This div will follow you as you scroll till break-point. After breakpoint it will be position absolute. In our example we will make a sidebar which will float till footer appears. We will not use any jQuery plugin to achieve this. It is simple code you can use in your website.

jquery floating div on scroll with example


First of all, include jQuery in your web-page ( Get CDN ) .

Basic Idea behind our code is:

  1. Write everything inside scroll function [ scroll() ].
  2. Calculate top and bottom offset of the floating block and save it in a variable.
  3. Also, top offset of the break point (here we are using footer as a break point).
  4. Calculate the height of the block.
  5. Take the current scrolling position of the scrollbar in a variable. So that, we can change the block’s position when window scrolls.


View Demo of the floating div made with jquery and css


About Chandan

Author View all posts by Chandan →

Leave a Reply

Your email address will not be published. Required fields are marked *