JS - get percentage of item in Viewport

I want to get the percentage of an element (div) when it is in the viewport.

  • when an item enters the viewport, I need a value of 0.
  • When the height of the element and the element leaves the viewport, I need a value of 100.

Here are 5 viewports of what I want to do http://imgur.com/2ZPpps5

I tried:

$(window).bind('scroll',function(){
var  viewportHeight = $(window).height(),
elementOffsetTop = $('#element').offset().top,
elementHeight = $('#element').height();

var numerator = 200 * (window.pageYOffset-elementOffsetTop+viewportHeight);
var denominator = (elementOffset+elementHeight+viewportHeight);
console.log(numerator/denominator);
});

This code works. (I do not understand why I need to multiply by 2).

But when I resize my page, this code does not work (value from 0 to 85 ...)

Ideas?

+4
source share
1 answer

http://jsfiddle.net/nate/4N3Pj/1/

var $element = $('#element');
var $win = $(window);
var $vis = $('#visible');

$win.on('scroll', function () {
    console.log(percentageSeen());
    $vis.text(percentageSeen() + '%');
});

function percentageSeen () {
    var viewportHeight = $(window).height(),
        scrollTop = $win.scrollTop(),
        elementOffsetTop = $element.offset().top,
        elementHeight = $element.height();


    if (elementOffsetTop > (scrollTop + viewportHeight)) {
        return 0;
    } else if ((elementOffsetTop + elementHeight) < scrollTop) {
        return 100;
    } else {
        var distance = (scrollTop + viewportHeight) - elementOffsetTop;
        var percentage = distance / ((viewportHeight + elementHeight) / 100);
        percentage = Math.round(percentage);
        return percentage;
    }
}

$win.trigger('scroll');
+7
source

All Articles