3

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);

});

2 Answers2

2

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/
Community
  • 1
  • 1
loxxy
  • 12,505
  • 2
  • 21
  • 52
  • 1
    no this is not what i want... they positioned relative... but when page scroll reach to that progress bar it should start filling up... –  Mar 18 '14 at 05:37
  • it starts filling up while scroll reach to screen that part is fine but every time i scroll it start from zero... it should be filled while scrolling down and start being empty moving up –  Mar 18 '14 at 07:06
  • the logic here is a bit more tedious.. but here you go http://jsfiddle.net/ddh3t/6/show – loxxy Mar 18 '14 at 09:03
1

Try this -

 $(window).scroll(function () {
var c = $(window).height();
  var progressLowerLimit=1000-c; //assuming the first progressbar to 1000px away from top.
if(progressLowerLimit<0)
    progressLowerLimit=0;
var s = $(window).scrollTop(),
d = $(document).height()-progressLowerLimit;

if(s<progressLowerLimit)
  return;
else
 s=s-progressLowerLimit;
scrollPercent = (s / (d-c)) * 100;
var position = scrollPercent;

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

updated fiddle

durgesh.patle
  • 640
  • 5
  • 22