Search code examples
javascriptjqueryhtmlhtml5-videolightbox

HTML5 Video: autoplay not working in lightbox


I am using html5 video tag for displaying video in a lightbox. The video itself works fine. But when i try to autoplay it when someone opens the lightbox i fail. Here is the javascript code i am using.

HTML to trigger lightbox which is working fine.

<a href="#" class="btn btn-blue lightbox btnlb">Watch the full video</a>    

HTML of video tag which is also working fine.

<video id="lbvideo" width="960" height="540">
    <source src="<?php bloginfo('template_directory'); ?>/videos/pinkgirl.mp4" type="video/mp4">
    <source src="<?php bloginfo('template_directory'); ?>/videos/pinkgirl.ogg" type="video/ogg">
    Your browser does not support HTML5 video.
</video>

Javascript code for autlplaying video on click of lightbox. Not working as expected.

$(".btnlb").click(function(e){
        var myVideo = document.getElementById("lbvideo"); 
        myVideo.play();
});

I have also tried using timeout after click, but that did not work.

$(".btnlb").click(function(e){
        setTimeout(function() {
        var myVideo = document.getElementById("lbvideo"); 
        myVideo.play();
        console.log(myVideo);
        }, 5000);
});

Solution

  • After working on this for a few hours, i found an alternative that did everything in minutes. I used afterglow which is a super easy to integrate HTML5 video player. With this simple setup i was all set and it looked really good.

    <!DOCTYPE html>
    <html>
      <head>
        <title>afterglow player</title>
        <script src="//cdn.jsdelivr.net/npm/[email protected]"></script>
      </head>
      <body>
        <a class="afterglow" href="#myvideo">Launch lightbox</a>
        <video id="myvideo" width="960" height="540">
          <source type="video/mp4" src="/path/to/myvideo.mp4" />
        </video>
      </body>
    <html>
    

    Sharing in case it helps someone else and saves them some time. Happy Coding. :)