Feb

12

Scrolling Floating Sidebar in jQuery

Posted by 11 Comments

Making a sidebar that floats while scrolling for your website is quite simple using jQuery. A very basic markup of HTML, CSS, and Javascript are below. Click on the JS Fiddle link at the bottom to view a demo.

HTML: Two divs, a longer ‘divA’ on the left, and the floating ‘divB’ on the right, both wrapped in a container div.

1
2
3
4
<div id="container">
    <div id="divA"></div>
    <div id="divB"></div>
</div>


CSS: Making the container long enough so the page scrolls.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#container {
    width: 100px;
    height: 2500px;
}
#divA {
    width: 30px;
    height: 500px;
    float: left;
    border: 1px solid;
}
#divB {
    width: 30px;
    height: 50px;
    float: right;
    border: 1px solid;
}

jQuery code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$sidebar = $("#divB");
$window = $(window);
var sidebarOffset = $sidebar.offset();
 
$window.scroll(function () {
    if ($window.scrollTop() > sidebarOffset.top) {
        $sidebar.stop().animate({
            marginTop: $window.scrollTop() - sidebarOffset.top
        });
    } else {
        $sidebar.stop().animate({
            marginTop: 0
        });
    }
});

To view the above example in action check out this JSFIDDLE.

Category: Development, JavaScript, jQuery, Web Development

Comments (11)

Trackback URL | Comments RSS Feed

  1. Jeremy says:

    Thanks, I was looking for something simple like this

  2. Dzagro says:

    mmmmm simple it will be good, thanks a lot :)

  3. Wajid Khan says:

    lovely code

  4. Adhy Suryadi says:

    Thank’s for the code, sir. I slightly modified to add a top margin and disable sticky on small devices, and it’s working perfectly.

  5. Kumar says:

    it’s working while scroll down a page, but i want to display default when i open my site also. how can i do this?

  6. Rafael says:

    Thank you, it’s working perfectly! But, how do I stop the animation while scrolling down? When I reach the bottom of the div, the height keeps increasing and the scroll goes on and on.

  7. Sreejit says:

    Thank you for the code…

  8. Ashish Singh says:

    Thanks for your code

    Sir i want left divB should scroll till the height of divA and should not scroll after that.

    currently divb scrolls with window even there is no content on left side

    Thanks

Leave a Reply