Search code examples
jqueryhtml5-videoonchange

jQuery detect if HTML5 autoplay video plays already?


I have a video element with a text overlay. I set the video to autoplay, but this can take some time when a user enters the site for the first time. For that case, I set up a poster image to display while the video hasn't started yet. What I want to achieve is, to hide/fade-out my video-overlay, as soon as the video starts playing.

My HTML looks like this:

  <div class="video-wrapper">    
      <div class="video-overlay">
         <h1>Lorem Ipsum</h1>
         <p>Lorem ipsum...</p>
      </div>
      <div class="video-container">
        <video poster="img/default_player.jpg" id="bgvid" playsinline autoplay muted loop>
            <source src="vdo/vdo_original.mp4" type="video/mp4">
        </video>
      </div>
   </div>

Is there any possiblity to detect with jQuery if the video started playing already, or is still buffering?

something like:

var video = jQuery("#bgvid").getState();

if ( video.paused ) {
    jQuery(".video-overlay").show();
} 

else {
    jQuery(".video-overlay").hide();
}

return false;

And binding this to a change function or similar? Thank you very much in advance!


Solution

  • As @Bilel pointed out, there are diffent ways to do this. I've chosen the way of an "on-play-function".

    which leaves me with this:

    var videocontainer = '#bgvid';
     
    jQuery(videocontainer).on('play', function() {
        jQuery('.video-overlay').fadeOut(400);
    });
    

    This works fine for me, because it fades away my overlay on play and is not needed later, because the video autoplays, loops and the controls are hidden.