<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Elememnt is Visible</title>
<style>
span{ position:fixed; top:0; left:0; }
.box{ width:100px; height:100px; background:red; margin:1000px; transition:2s; }
.visible{ background:green; border-radius:50%; }
</style>
</head>
<body>
<span>Scroll both Vertically & Horizontally...</span>
<div class='box'></div>
<script>
// Just another way
function isInViewport (element) {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
// Event base process
var Observer = new IntersectionObserver(function(entries) {
// If intersectionRatio is 0, the target is out of view
// and we do not need to do anything.
if (entries[0].intersectionRatio == 0) {
// this how you get the first element from the observe method (*)
document.title = 'Item is Not visible';
var el = document.getElementsByClassName("box");
el[0].classList.remove("visible");
} else {
document.title = 'Item IS visible';
var el = document.getElementsByClassName("box");
el[0].classList.add("visible");
}
});
// start observing
Observer.observe(document.querySelector('.box')); // check entries for data structure (*)
</script>
<span>Scroll both Vertically & Horizontally...</span>
<div class='box'></div>
</body>
</html>