Blog for web designers

Follow sidebar to top on scroll

Ever wonder what it looks like if you have a entire vertical space for sidebar and you have only one widget to show in there in so long pages ?
Well this will make embarrassing because when you keep scroll down you will see a lot of blank space in the sidebar which is really bad. I have come up with a very good solution that will help you to follow sidebar to top on scroll of the web pages. With the simple jQuery code it is possible to maintain the blank space in the sidebar. What we are going to do is, we will animate the sidebar to the top of the web page whenever the user scroll down to view more content. This will help user to keep an eye on the sidebar widget and utilized the blank space too. Let me show you how you can do this.

jQuery code to Follow sidebar to top on scroll


$(document).ready(function(){
    var offset = $("#single_widget").offset();
    var mbOffset = $(".footer").offset(); // stop the single_widget to scroll when it reach footer
    var mbPos = mbOffset.top - $("#single_widget").outerHeight() - 30; /*30px extra space*/
    var topPadding = 15;
    $(window).scroll(function() {
        if ($(window).scrollTop() > offset.top ) {
            if(  $(window).scrollTop() < mbPos ) {
                $("#single_widget").stop().animate({
                    marginTop: $(window).scrollTop() - offset.top + topPadding
                });
            }
        } else {
            $("#single_widget").stop().animate({
                marginTop: 0
            });
        };
    });
});

Santosh Shah

My name is Santosh Shah and blogs at santosh-shah.com


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.