intersectionObserve

HTML
<script src="https://cdn.jsdelivr.net/npm/intersection-observer@0.12.0/intersection-observer.js"></script> <section class="item"> <h1>Item 1</h1> </section> <section class="item"> <h1>Item 2</h1> </section> <section class="item"> <h1>Item 3</h1> </section>
CSS
body { height: 100vh; margin: 0; } section { width: 1000%; margin: 0 auto; height: 100vh; } h1 { margin: 0px; padding: 0px; }
JAVASCRIPT
document.addEventListener("DOMContentLoaded", function(){ //Stop if no support - IE11 var isIE11 = !!window.MSInputMethodContext && !!document.documentMode; if (isIE11) { return false; } //Configure observer const options = { //root: null //the viewport //threshold: 0, // 0-1 | 1 means 100 % of the item must be in the viewport //rootMargin: , //distance into vewport } //Build an observer observer = new IntersectionObserver((entries) => { //Loop through all the entries found entries.forEach(entry => { //Get this enties h1 text var itemName = entry.target.querySelector("h1").innerHTML; if(entry.intersectionRatio > 0) { console.log("enter - " + itemName) } else { console.log("leave - " + itemName) } }) }, options); //Find all the sections with class item const items = document.querySelectorAll('.item'); //Loop through all the classes and add an observer items.forEach(item => { observer.observe(item) }); });
Expand for more options Login