Determining the percentage on the item screen

I am trying to determine which% of the item can be seen in the current window.

For example, if the user can only see half of the item, return 50. If the user can see the whole item, return 100.

Here is my code:

function getPercentOnScreen() {
    var $window = $(window),
        viewport_top = $window.scrollTop(),
        viewport_height = $window.height(),
        viewport_bottom = viewport_top + viewport_height,
        $elem = $(this),
        top = $elem.offset().top,
        height = $elem.height(),
        bottom = top + height;

    return (bottom - viewport_top) / height * 100;
}

But it does not seem to work. Can anyone help me with this, I seem to be spinning.

+4
source share
3 answers

What you want to get is the number of pixels that the element passes at the top and bottom of the viewport. Then you can simply subtract it from the total height and divide by this height to get a percentage image on the screen.

var px_below = Math.max(bottom - viewport_bottom, 0);
var px_above = Math.max(viewport_top - top, 0);
var percent = (height - px_below - px_above) / height;
return percent;

, jQuery . , , .outerHeight .

+1

$elem = $(this) , scoping , this , (ala ~ getPercentOnScreen), $elem = $('#yourElementId').

0

if you only want to calculate the percentages of an element, just do it

function getPercentOnScreen(elem) {
    $docHeight = $(document).height();
    $elemHeight  = $(elem).height();

    return ($elemHeight/$docHeight)* 100;
}
-1
source

Source: https://habr.com/ru/post/1540259/


All Articles