Code Snippets
/

Check if an Element Is in the Viewport

Check if an Element Is in the Viewport

Lazy-loading images, animating sections on enter, and infinite scroll all start with the same question: is this element on screen? The classic answer was a scroll handler plus `getBoundingClientRect`, but `IntersectionObserver` is now the right tool: passive, batched, and rate-limited by the browser. This snippet covers the synchronous bounds check, the async observer-based watcher, and a one-shot helper that resolves once a target enters the viewport.

JavaScript
Medium
3 snippets
js-web-apis
js-dom
performance-optimization
utility

512 views

11

function isInViewport(el) {
    const rect = el.getBoundingClientRect();
    const vh = (typeof window !== 'undefined' && window.innerHeight) || 0;
    const vw = (typeof window !== 'undefined' && window.innerWidth) || 0;
    return rect.top < vh && rect.bottom > 0 && rect.left < vw && rect.right > 0;
}

const node = document.createElement('div');
console.log('in viewport (stub):', isInViewport(node));

Comparing getBoundingClientRect() against innerHeight and innerWidth is the simplest check: any overlap between the element's rect and the viewport rectangle counts as visible. The four conditions cover top-clipped, bottom-clipped, left-clipped, and right-clipped cases without missing partial visibility. The catch is that getBoundingClientRect triggers layout, so calling it inside a scroll handler on every event will jank the page. Use this only for one-off checks; reach for the observer when the answer needs to update over time.