I want to get the percentage of an element (div) when its in viewport.
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 don't understand why I have to multiply by 2).
But when I resize my page, this code not works ( value between 0 to 85 ... )
Ideas?
My version is slightly different. When the element is higher than the screen height itself, it interprets that as 100% in viewport.
For example, if the screen height is 1000 pixels and the element is 2000 pixels height and it is scrolled fully into view, the function will return 100% instead of the normal 50%.
Enjoy.
var percentWithinViewport = function (element) {
var elementTop = element.offset().top;
var scrollTop = $(window).scrollTop();
var spaceTop = elementTop - scrollTop;
var elementHeight = element.height();
var screenHeight = $(window).height();
var scrollBottom = scrollTop + screenHeight;
var bottomElement = elementTop + element.height();
var spaceBottom = bottomElement - scrollBottom;
var heightInScreen = elementHeight - spaceBottom;
var percentage;
if (spaceTop < 0) {
heightInScreen -= spaceTop * -1;
}
if (spaceBottom < 0) {
heightInScreen -= spaceBottom * -1;
}
percentage = heightInScreen / screenHeight * 100;
percentage = percentage < 0 ? 0 : percentage;
element.attr('data-percent-viewport', percentage);
return percentage;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With