skip to Main Content

Im using a script to play a html5 video once an element is in viewport. Once the video is played I want it to remain paused, but once I start scrolling the video start playing again. Any idea how to trigger play only once?

Script:

jQuery.fn.isInViewport = function() {
    var elementTop = jQuery(this).offset().top;
    var elementBottom = elementTop + jQuery(this).outerHeight();

    var viewportTop = jQuery(window).scrollTop();
    var viewportBottom = viewportTop + jQuery(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};

jQuery(window).on('resize scroll', function() {
    if (jQuery('.videoblock').isInViewport()) {
jQuery('video.full_screen_sections_video').trigger('play');
    } 
});

Edit: I added jQuery(this).removeClass('videoblock'); to my the function. This solves it, not sure of thats the best way to do it?

2

Answers


  1. You could just remove the event listener which is starting the video after it is in viewport:

    jQuery(window).on('resize scroll', function() {
        if (jQuery('.videoblock').isInViewport()) {
          jQuery('video.full_screen_sections_video').trigger('play');
          // Remove the event listener once the video is started
          jQuery(window).off('resize scroll');
        } 
    });
    Login or Signup to reply.
  2. Adding jQuery(this).removeClass(‘videoblock’); will remove the videoblock class from the element that is in the viewport, which will prevent the if condition from being true on subsequent scrolls. However, this solution may not be the most efficient, as it modifies the DOM on every scroll event, which can slow down the performance of your page.

    A more efficient solution would be to use a flag variable to keep track of whether the video has already been played or not. Here’s an example code :

     var videoPlayed = false;
    
      jQuery(window).on('resize scroll', function() {
      if (jQuery('.videoblock').isInViewport() && !videoPlayed) {
       jQuery('video.full_screen_sections_video').trigger('play');
       videoPlayed = true;
      }
      });
    

    In this code, the videoPlayed variable is initialized to false. When the video is played for the first time, the videoPlayed variable is set to true, and the video won’t play again on subsequent scrolls because the if condition will fail. This solution avoids modifying the DOM on every scroll event, which should improve the performance of your page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search