How to start background video only when it is in view

I am looking to know if there is a setting in Webflow or Custom Code to make the videos play only when they are in view. I have a number of videos on my site and when I scroll down to them its already half way through the animation.

@Derrek_Hennessy - There is no built-in feature to handle this in Webflow so you need leverage custom code. You could use JavaScript to play and pause while a video is in view. I have used GSAP ScrollTrigger before to do this. You could use vanilla JS as well. I am sure there are demo’s and tuts on YouTube.

In the settings panel, give your video element a custom ID. In the code below, change ‘yourVideoID’ with whatever ID you gave your video. In custom code section of your page or site, put the code below in the “Before closing body tag” area.

<script>
document.addEventListener("DOMContentLoaded", function() {
  var videoHasBeenPlayed = false; // Flag to check if video has played
  var video = document.getElementById('yourVideoID'); // Replace 'yourVideoID' with your actual video ID

  function playVideoOnScroll() {
    if (videoHasBeenPlayed) return; // Stop function if video has already played

    var videoRect = video.getBoundingClientRect();
    var videoVisible = (videoRect.top <= window.innerHeight) && ((videoRect.top + videoRect.height) >= 0);

    // Play the video if it's visible
    if (videoVisible) {
      video.play();
      videoHasBeenPlayed = true; // Update flag so video doesn't play again
    }
  }

  window.addEventListener('scroll', playVideoOnScroll);
  playVideoOnScroll(); // Check if video is initially in view
});
</script>
1 Like

Hey Jonathan,
thank you for the script! Exactly what I have been looking for!

Is there any way to add an offset to this, so that the video not starts playback at the first visible row of pixels but rather after let’s say 50px of visibility in the viewport or a certain percentage? Same would be awesome for “scrolling out of view” so that playback stops when the majority of the video has been scrolled out of viewport.

Would be a blast if you could help.

Cheers,
Michi