IntersectionObserver
by John Doe
HTML
<div id="wrapper">
<div id="slides">
<div class="slide slide1">slide1</div>
<div class="slide slide2">slide2</div>
<div class="slide slide3">slide3</div>
</div>
</div>
CSS
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#wrapper {
position: absolute;
height: 100%;
width: 100%;
}
#slides {
scroll-snap-type: y mandatory;
overflow: auto;
height: 100vh;
}
.slide {
scroll-snap-align: start;
height: 100vh;
}
.slide1 {background-color: red;}
.slide2 {background-color: green;}
.slide3 {background-color: blue;}
JavaScript
const observer = new IntersectionObserver(callback, {
//root: slidebar,
root: null,
// rootMargin:'0px',
threshold: 1.0
});
function callback(evt) {
let visible = evt.filter(el=>el.intersectionRatio === 1);
if (visible.length) {
console.log('chosen one', visible[0].target);
}
}
const slidebar = document.querySelector('#slides');
document.querySelectorAll('.slide').forEach((slide) => {
observer.observe(slide)
})