Use of the IntersectionObserver to check when an element is intersecting with the viewport.
View sample on JsFiiddle
Use of the IntersectionObserver to check when an element is intersecting with the viewport.
View sample on JsFiiddle
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<title>Check if an element is in the viewport</title> | |
<meta name="description" content="Use of the IntersectionObserver to check when an element is intersecting with the viewport." /> | |
<style> | |
body { font-family: sans-serif; } | |
#dn { color: red; } | |
#up { color: blue; } | |
#target { | |
background-color: #f0f0f0; | |
border-bottom: 2px solid #ccc; | |
padding: 1rem; | |
} | |
</style> | |
</head> | |
<body> | |
<p id="dn">↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓<br /><br />↓↓↓↓↓</p> | |
<p id="target">I am out of space...</p> | |
<p id="up"> ↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑<br /><br />↑↑↑↑↑</p> | |
<script> | |
let observer = new IntersectionObserver(function (doms, obs) { | |
doms.forEach(function (entry) { | |
let hasIntersecting = entry.isIntersecting; | |
let purpose = entry.target; | |
if (!hasIntersecting) return; | |
purpose.textContent = "Hip, hip - hooray.. I am in :o)"; | |
console.log("When the target will enter into the viewport: ", hasIntersecting ? "Right now is in!" : "I do not know?!"); | |
// Stop observing after the first occur | |
obs.unobserve(purpose); | |
}); | |
}); | |
let target = document.querySelector('#target'); | |
observer.observe(target); | |
</script> | |
</body> | |
</html> |