👋 Hello! I'm Alphonsio the robot. Ask me a question, I'll try to answer.
In JavaScript, how to check if an element is in the viewport?
The following function returns true
if the element el
i s in the viewport:
// Return true if the element el is in viewport
function isInViewport(el) {
var distance = el.getBoundingClientRect();
return (
distance.top >= 0 &&
distance.left >= 0 &&
distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
distance.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};