Skip to content

@mataspetrikas /gist:2300296
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Check if the DOM node is visible in the viewport
function elementInViewport(el) {
var rect = el.getBoundingClientRect()
return rect.top < (window.innerHeight || document.body.clientHeight) && rect.left < (window.innerWidth || document.body.clientWidth);
}
// and then you can use it:
alert(elementInViewport(document.getElementById('inner')));
// or
alert(elementInViewport($('#inner')[0]));​
`
@MiniDude22

Forgot your semicolon after the variable declaration.

@ctbarna

This fails if an element is above or to the left of the viewport. When rect.top or rect.left are negative, the respective clauses will still pass regardless of the values of rect.bottom or rect.right.

@ctbarna

This is the code I use:

return (
    (boundingRect.top >= 0 ||
        boundingRect.bottom <= window.innerHeight) &&
    (boundingRect.left >= 0 ||
        boundingRect.right <= window.innerWidth)
);
@ucavus

Try this:

return rect.bottom > 0 &&
        rect.right > 0 &&
        rect.left < (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */ &&
        rect.top < (window.innerHeight || document.documentElement.clientHeight) /*or $(window).height() */;

Both previous solutions have the algebra wrong. Think about it, the top of an element can be above the top of viewport, but if the bottom of the element is showing (i.e. is below the top of the viewport), then it is still visible. Likewise for horizontal calculations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.