Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save rattrayalex/8529d49686d52b6cf40e48cd27220e6a to your computer and use it in GitHub Desktop.

Select an option

Save rattrayalex/8529d49686d52b6cf40e48cd27220e6a to your computer and use it in GitHub Desktop.
Vanilla JS ES6 snippet to play html5 video on scroll into view or click (and pause when out of view or clicked while playing)
function debounce(callback) {
let timeout = null;
return function() {
const next = () => callback.apply(this, arguments);
cancelAnimationFrame(timeout);
timeout = requestAnimationFrame(next);
}
}
const observerOptions = {
threshold: 0.5, // trigger only when this % of element comes into view
};
const viewportObserver = new IntersectionObserver(debounce((entries, observer) => {
entries.forEach(entry => {
const video = entry.target;
if (entry.isIntersecting && video.dataset.paused !== 'true') {
video.play();
} else {
video.pause();
}
})
}), observerOptions);
document.querySelectorAll('video').forEach((video) => {
viewportObserver.observe(video);
video.addEventListener('click', () => {
if (video.paused) {
video.dataset.paused = 'false'
video.play();
} else {
video.dataset.paused = 'true'
video.pause();
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment