Search code examples
htmlvideofancybox

Autoplay HTML5 video with Fancybox3


I want to autoplay an HTML5 video after opening it on fancybox3.

here's my codepen: https://codepen.io/ableslayer/pen/aygGQX

and my code:

$(document).ready(function() {
    $("[data-fancybox]").fancybox({
      afterShow: function() {
        // After the show-slide-animation has ended - play the vide in the current slide
        this.content.find('video').trigger('play')

        // Attach the ended callback to trigger the fancybox.next() once the video has ended.
        this.content.find('video').on('ended', function() {
          $.fancybox.next();
        });
      }
    });
  });

Solution

  • Give your video a id (myVideo) and add this line in afterShow function

    var vid = document.getElementById("myVideo"); 
     vid.play(); 
    

    Javascript

    $(document).ready(function() {
        $("[data-fancybox]").fancybox({
          afterShow: function() {
            // After the show-slide-animation has ended - play the vide in the current slide
           var vid = document.getElementById("myVideo"); 
           vid.play(); 
    
            // Attach the ended callback to trigger the fancybox.next() once the video has ended.
            this.content.find('video').on('ended', function() {
              $.fancybox.next();
            });
          }
        });
      });
    

    HTML

    <a data-fancybox data-src="#one" class="fancybox">link</a>
    <div id="one" style="display:none">
      <video id='myVideo' width="400" controls autoplay>
      <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">          
      Your browser does not support HTML5 video.
      </video>
    </div>