How to create a floating div on scroll with jQuery
Posted on by ChandanWe 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.
First of all, include jQuery in your web-page ( Get CDN ) .
Basic Idea behind our code is:
- Write everything inside scroll function [ scroll() ].
- Calculate top and bottom offset of the floating block and save it in a variable.
- Also, top offset of the break point (here we are using footer as a break point).
- Calculate the height of the block.
- Take the current scrolling position of the scrollbar in a variable. So that, we can change the block’s position when window scrolls.
Leave a Reply