Skip to content

Instantly share code, notes, and snippets.

@kankadev
Last active March 15, 2023 17:43
Show Gist options
  • Save kankadev/6313fe1964da28fb3c07810d0ccda3ce to your computer and use it in GitHub Desktop.
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
$(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