Scroll · 30 of 34
Video Play
A video plays when it scrolls into view and pauses when it leaves, saving bandwidth and battery. IntersectionObserver calls play() and pause().
<!-- Swap the placeholder for a real <video muted playsinline> to
auto play/pause it — see the commented lines in the JS -->
<section class="video-scroll-section">
<div class="video-placeholder">Video Play/Pause</div>
</section>
.video-scroll-section {
min-height: 35vh;
display: flex;
align-items: center;
justify-content: center;
}
.video-placeholder {
width: 300px;
height: 180px;
background: #000;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #333;
transition: border-color 0.5s, color 0.5s;
}
.video-scroll-section.in-view .video-placeholder {
border-color: #7c5cff;
color: #7c5cff;
}
var section = document.querySelector('.video-scroll-section');
// var video = document.querySelector('.video-scroll-section video');
new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
entry.target.classList.toggle('in-view', entry.isIntersecting);
// With a real <video> element, play while visible and pause otherwise:
// if (entry.isIntersecting) video.play(); else video.pause();
});
}, { threshold: 0.25 }).observe(section);