Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ihorduchenko/64b47a1268b20784957584caf5010358 to your computer and use it in GitHub Desktop.
Save ihorduchenko/64b47a1268b20784957584caf5010358 to your computer and use it in GitHub Desktop.
Toggle video play on screen intersection + on click
<div class="absolute-cover video-cover controlled-video autoplayLazyVideo">
<video
{% if img != blank %}
poster="{{ img.src }}"
{% endif %}
playsinline
loop
muted>
<source
src="{{ video.src }}"
type="video/mp4">
</video>
<div class="controlled-video--trigger absolute-cover autoplayLazyVideoTrigger">
<div class="controlled-video--trigger-text-play">
<div class="flex-align-center">
{% render 'icon', icon: 'play-outline-circle' %}
<span>Play now</span>
</div>
</div>
<div class="controlled-video--trigger-text-pause">
{% render 'icon', icon: 'pause-simple' %}
</div>
</div>
</div>
<script>
var autoplayLazyVideo = document.querySelectorAll('.autoplayLazyVideo');
var autoplayLazyVideoTrigger = document.querySelectorAll('.autoplayLazyVideoTrigger');
if ('IntersectionObserver' in window) {
autoplayLazyVideoTrigger && autoplayLazyVideoTrigger.forEach(function(trgr) {
let wrapper = trgr.closest('.autoplayLazyVideo');
let video = wrapper && wrapper.querySelector('video');
trgr.addEventListener('click', function() {
if (video) {
video.paused ? video.play() : video.pause();
}
wrapper.classList.toggle('is-stopped');
})
});
function handleAutoPlayVideos(entries) {
entries.map((entry) => {
let elem = entry.target;
let video = elem && elem.querySelector('video');
if (! elem.classList.contains('is-stopped')) {
if (entry.isIntersecting) {
entry.target.classList.add('is-playing');
video && video.play();
} else {
entry.target.classList.remove('is-playing');
video && video.pause();
}
}
});
}
const autoPlayVideosObserver = new IntersectionObserver(handleAutoPlayVideos);
autoplayLazyVideo && autoplayLazyVideo.forEach(function(video) {
autoPlayVideosObserver.observe(video);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment