Last active
March 15, 2023 17:43
-
-
Save kankadev/6313fe1964da28fb3c07810d0ccda3ce to your computer and use it in GitHub Desktop.
[Play video automatically if it's in viewport] This script plays a video automatically if it's visible in the viewport and it's paused if you scroll further. Add the class "knk-autoplay" to the videos parent div. #divi #jquery #wordpress #video
This file contains hidden or 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() { | |
const autoplayVideos = $('.knk-autoplay .et_pb_video_box'); | |
if (autoplayVideos.length) { | |
autoplayVideos.find('video').prop('muted', true) | |
.attr({ | |
loop: 'loop', | |
playsInline: '' | |
}); | |
const observerOptions = { | |
root: null, | |
rootMargin: '0px', | |
threshold: 0.5 | |
}; | |
const videoObserver = new IntersectionObserver((entries, observer) => { | |
entries.forEach((entry) => { | |
entry.isIntersecting ? entry.target.play() : entry.target.pause(); | |
}); | |
}, observerOptions); | |
autoplayVideos.each(function() { | |
videoObserver.observe($(this).find('video')[0]); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment