Search code examples
javascripthtml5-videoviewportautoplayintersection-observer

Intersection observer for multiple videos on the same page


I have a portfolio page made in WordPress and on the page I have 5 videos that need to be played when in viewport and stopped when out of viewport.

I have used the following script that works only on the first video on the page.

const video = document.querySelector("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);
querySelector("video");

And here is the link to the page: http://wemedia.co.rs/portfolio-2/

So what I want to achieve is to play and pause every video when in or out of viewport.

Thank you.


Solution

  • You are only selecting one video to use throughout your whole js script.

    You need to remember that video represents only a single video and if you want to control multiple, you need to reference them in every function that you call.

    I also don't see a purpose in using playState since the way you have it, it is basically an indicator of whether the first video is on screen or not.

    const videos = document.querySelectorAll("video"); // Select ALL the Videos
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) {
          entry.target.pause(); // Pause the TARGET video
        } else {
          entry.target.play(); // Play the TARGET video
        }
      });
    }, {});
    for (const video of videos) observer.observe(video); // Observe EACH video
    const onVisibilityChange = () => {
      if (document.hidden) {
        for (const video of videos) video.pause(); // Pause EACH video
      } else {
        for (const video of videos) video.play(); // Play EACH video
      }
    };
    document.addEventListener("visibilitychange", onVisibilityChange);