Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element is visible for certain percentage on screen (viewport)?

How can i detect if some element is visible? For better understading look at the image below.

Screen with half-visible image

I want to fire event when the image is half-visible. It would be great if it would work for all browsers and devices (tablets and smartphones).

like image 446
Manny Avatar asked Mar 28 '14 10:03

Manny


People also ask

How do you know if a element is visible in a viewport?

Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.

How much of an element is visible in viewport?

So even if it's a part of a element but it covers the full height of the screen, it should be 100% in viewport.

How do I get the viewport element?

To find out if the whole element is inside of the viewport we can simply check if the top and left value is bigger or equal to 0, that the right value is less or equal to the viewport height ie window. innerWidth and that the bottom value is less or equal to window. innerHeight.

Is element in viewport jQuery?

Check if element is visible in viewport using jquery:If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially).


2 Answers

Jquery.fracs plugin seems to do exactly what you need.

function callback(fracs: Fractions, previousFracs: Fractions) {
    if(fracs > 0.5)
      doSomething();
};

var fracs = $("img").fracs(callback);
like image 122
Max Al Farakh Avatar answered Sep 22 '22 06:09

Max Al Farakh


Your Window is between

$(document).scrollTop()

and

$(document).scrollTop() + $(window).height()

If the

$(element).offset().top

falls between those, it should be visible.

EDIT: I am assuming your element (whose visibility is to be determined) is absolutely positioned. If not, it would be a bit more complicated.

EDIT2: This is only to determine visibility in case of vertical offset. For the horizontal version, replace "scrollTop" with "scrollLeft", "height" with "width" and "top" with "left".

like image 21
Emanuele Ciriachi Avatar answered Sep 23 '22 06:09

Emanuele Ciriachi