Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rattrayalex/8529d49686d52b6cf40e48cd27220e6a to your computer and use it in GitHub Desktop.
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