Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Progress bar should start filling up when visible on screen

While scrolling down the page, progress bar are filled up. But what I want they should b start filling up while they are visible on screen. How to achieve that?

Fiddle

$(window).scroll(function () {
  var s = $(window).scrollTop(),
        d = $(document).height(),
        c = $(window).height();
        scrollPercent = (s / (d-c)) * 100;
        var position = scrollPercent;

   $("#progressbar").attr('value', position);
    $("#progressbar2").attr('value', position);

});

1 Answers

Assumption 1: You wish them to be always visible on the screen. A bit of CSS tweak will do:

progress {
    top:10px;
    position:fixed;
    right:10px;
}
#progressbar2 {
    top: 40px;
}

DEMO : http://jsfiddle.net/ddh3t/1/


Assumption 2: You want an animated fill, when the progress bar is visible. This requires change in JS:

(isScrolledIntoView from here).

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();
    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function () {
    var s = $(window).scrollTop(),
        d = $(document).height(),
        c = $(window).height();
    scrollPercent = (s / (d - c)) * 100;
    var position = scrollPercent;

    var p1 = $("#progressbar"), p2 = $("#progressbar2");

    if(isScrolledIntoView(p1)) {
        var val = 0, delay = 32, timer;        
        timer = setInterval(function() {
            p1.attr('value', val++);
            if(val>=position) clearInterval(timer);
        },delay);

    }
});

DEMO : http://jsfiddle.net/ddh3t/3/

Note that p2 (the second progress bar) can be filled similarly.


Final Update : http://jsfiddle.net/ddh3t/6/
like image 152
loxxy Avatar answered Jan 02 '26 04:01

loxxy