Site logo

Archived topic

background video playing on viewport

9 replies · Started by Salty Communication on December 6, 2022

Viewing posts 1–10 of 10

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 Fernando, sure!

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.

This archived topic is closed to new replies.