Skip to content

Instantly share code, notes, and snippets.

@BhargavBhandari90
Created May 28, 2024 11:37
Show Gist options
  • Save BhargavBhandari90/ec7c8fd23a7cfd898c90fed3ad9989f1 to your computer and use it in GitHub Desktop.
Save BhargavBhandari90/ec7c8fd23a7cfd898c90fed3ad9989f1 to your computer and use it in GitHub Desktop.
Play video when in view part
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