Archived topic
background video playing on viewport
9 replies · Started by Salty Communication on December 6, 2022
Hi!
Used this: https://docs.generatepress.com/article/background-video/ and got everything working. But, is there a way to start the video when the block is in the viewport instead of autoplaying when loading?
Thanks!
-J
Hi there,
it would require Javascript to do that.
1. remove the autoplay attribute from the video html.
2. after the HTML add this script:
<script>
const video = document.querySelector(".background-video");
let playState = null;
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) {
video.pause();
playState = false;
} else {
video.play();
playState = true;
}
});
}, {});
observer.observe(video);
const onVisibilityChange = () => {
if (document.hidden || !playState) {
video.pause();
} else {
video.play();
}
};
document.addEventListener("visibilitychange", onVisibilityChange);
</script>
3. keep fingers crossed....
I did cross my fingers.. but it didnt work. Do I have to enque the JS in some way maybe?
-J
Hello there,
For reference, can you provide the link to the site in question?
You may use the Private Information field for this: https://docs.generatepress.com/article/using-the-premium-support-forum/#private-information
Hello Fernando, sure!
Can you try adding the script through a Hook Element hooked to wp_footer?
Reference: https://docs.generatepress.com/article/hooks-element-overview/
Done! Doesnt play..
I made an edit to the code above ie.
this line:
const video = document.querySelector("background-video");
became:
const video = document.querySelector(".background-video");
Nice! We got it. Thanks!
Awesome - glad to hear that.