Detect a DOM element is visible in the current viewport?
On any web application, lazy loading became a standard for almost anything. It is an image, an ad, or a video we want resources to be lazy-loaded. To do the lazy loading it is necessary to detect a DOM element is in the viewport or not. Following is the function the detects an element is on viewport or not.
Function definition
var isElementVisibleOnViewport = function(el) { if (typeof jQuery === "function" && el instanceof jQuery) el = el[0]; var rect = el.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); };
Function call
isElementVisibleOnViewport($('#element-id')); // jQuery call isElementVisibleOnViewport(document.getElementById('element-id')); // JavaScript call