How can i detect if some element is visible? For better understading look at the image below.
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).
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.
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.
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.
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).
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);
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".
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