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?
source
share