[SOLVED] Play/Pause a Video with Scroll Trigger?

Hey everyone,
How do you start a video when it enters the viewport and pause it when it leaves the viewport?

I’m not talking about a scrolling video

Thanks

You can also use something similar using the Intersection Observer API:

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");

Here’s an example.

1 Like

Just use the Bricksforge Panel Events for this. There are “Play Video” and “Stop Video” actions :slight_smile:

1 Like

Hey @Daniele I tried that, but it doesn’t work…

Thank you for that! I tested it but unfortunately without success.
I also adapted the script but it just doesn’t work…
I don’t know if Bricks intervenes somehow.

<script>
  const videoElements = document.querySelectorAll('video');

  const options = {
    threshold: 0.1
  };

  function videoInViewport(entries, observer) {
    entries.forEach(entry => {
      const video = entry.target;

      if (entry.isIntersecting) {
        video.play();
      } else {
        video.pause();
      }
    });
  }

  const observer = new IntersectionObserver(videoInViewport, options);

  videoElements.forEach(video => {
    observer.observe(video);
  });
</script>

Working with this one. Maybe my fault because i have added the Script inline and not before the Body closing… :slight_smile:

<script>
// Define the options for the Intersection Observer
let options = {
    root: null,             // Use the viewport as the root
    threshold: 1.0          // Trigger when the entire target is in the viewport
};

// Callback function that runs when the intersection changes
let callback = (entries, observer) => {
    entries.forEach(entry => {
        // Check if the target element is a <video> element
        if (entry.target.tagName === 'VIDEO') {
            // If it's intersecting, play the video
            if (entry.isIntersecting) {
                entry.target.play();
            } else {
                // If it's not intersecting, pause the video
                entry.target.pause();
            }
        }
    });
};

// Create a new Intersection Observer with the callback and options
let observer = new IntersectionObserver(callback, options);

// Select all <video> elements on the page and add them to the observer
document.querySelectorAll('video').forEach(video => {
    observer.observe(video);
});
</script>

@Daniele i’m still interested in how it works with the BF events! :wink:

1 Like