How to test if an element is in the viewport with vanilla JavaScript

https://gomakethings.com/how-to-test-if-an-element-is-in-the-viewport-with-vanilla-javascript/ https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

by momenelkamri

HTML

<figure data-image="https://teeshirtpalace-production.s3.amazonaws.com/spree/images/NGUB342-BLACK-POST/large/NGUB342-BLACK-POST.jpg?1557343471">My image will go here...</figure>

JavaScript

var isInViewport = function (elem) {
    var bounding = elem.getBoundingClientRect();
    return (
        bounding.top >= 0 &&
        bounding.left >= 0 &&
        bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
};

var image = document.querySelector('[data-image]');
window.addEventListener('scroll', function (event) {
	if (isInViewport(image)) {
		image.innerHTML = '<img src="' + image.getAttribute('data-image') + '">';
	}
}, false);

var image = document.querySelector('[data-image]');

if (isInViewport(image)) {
  image.innerHTML = '<img src="' + image.getAttribute('data-image') + '">';
}

/* window.addEventListener('scroll', function (event) {
console.log(event);
	if (isInViewport(image)) {
		image.innerHTML = '<img src="' + image.getAttribute('data-image') + '">';
	}
}, false);
*/