Search code examples
javascriptjquerycssscrollbarsticky

Div to follow scrollbar proportionally on a page


I'm now struggling on a sticky element that should scroll proportionally on a page. From top to the footer despite the page's height. So it's actually stick to the top of the scrollbar in the beginning and then to the bottom at the end. Or it just follows the scroll wheel.

Is there any chance to do it with jQuery ?

Below is the starting code with usual "sticky" div.

$(window).scroll(function(){
$("#sticky")
.animate({"marginTop":($(window).scrollTop())+"px"}, "fast");});

https://jsfiddle.net/flakessp/cxr78xc8/


Solution

  • Do you mean something like this?

    $(window).scroll(function() {
    
        // calculate the percentage the user has scrolled down the page
        var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
    
        // get the height of the sticky element
        var stickyHeight = $('.sticky').height();
    
        // calculate the margin top of the sticky element
        var marginTop = (($(window).height() - stickyHeight) / 100) * scrollPercent;
    
        // set margin top of sticky element
        $('.sticky').css('marginTop', marginTop);
    });
    

    Fiddle