Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - get percentage of an element in Viewport

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

  • when the element enter the viewport I want the value of 0.
  • when the element and element's height leave the viewport I want the 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 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?

like image 723
youyoup Avatar asked Nov 26 '13 16:11

youyoup


1 Answers

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;
};
like image 57
Floris Avatar answered Oct 22 '22 22:10

Floris