Created
May 28, 2024 11:37
-
-
Save BhargavBhandari90/ec7c8fd23a7cfd898c90fed3ad9989f1 to your computer and use it in GitHub Desktop.
Play video when in view part
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
document.addEventListener('DOMContentLoaded', function() { | |
const video = document.getElementById('video-22_html5_api'); // SET your Video tag ID | |
let previewStarted = false; | |
function isElementInViewport(el) { | |
const rect = el.getBoundingClientRect(); | |
return ( | |
rect.top >= 0 && | |
rect.left >= 0 && | |
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && | |
rect.right <= (window.innerWidth || document.documentElement.clientWidth) | |
); | |
} | |
function playPreview() { | |
if (isElementInViewport(video) && !previewStarted) { | |
video.currentTime = 0; | |
video.play(); | |
previewStarted = true; | |
setTimeout(() => { | |
video.pause(); | |
}, 5000); // stop after 5 seconds | |
} else if (!isElementInViewport(video) && previewStarted) { | |
video.pause(); | |
previewStarted = false; | |
} | |
} | |
window.addEventListener('scroll', playPreview); | |
window.addEventListener('resize', playPreview); | |
});/* This is your custom Javascript */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment