Question #30   Submitted by Answiki on 05/03/2020 at 10:14:43 AM UTC

In JavaScript, how to check if an element is in the viewport?

Answer   Submitted by Answiki on 06/20/2020 at 03:15:03 AM UTC

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)
	);
};

5 events in history
Answer by Answiki on 06/20/2020 at 03:15:03 AM

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)
	);
};

Answer by Answiki on 05/03/2020 at 11:03:38 AM

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)
	);
};

Answer by Answiki on 05/03/2020 at 10:20:01 AM

The following function returns true if the element el is 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)
	);
};

Answer by Answiki on 05/03/2020 at 10:16:27 AM

The following function returns true if the element el is 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)
	);
}

Question by Answiki 05/03/2020 at 10:14:43 AM
In JavaScript, how to check if an element is in the viewport?
# ID Query URL Count

Icons proudly provided by Friconix.