Created
November 22, 2020 13:25
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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