Search code examples
jqueryyoutube-javascript-apimagnific-popup

Autoplay youtube video when video appears in a certain container


<div class="lightbox-trigger"></div>

<div class="lightbox-content autoplay"><iframe>...</iframe></div>

<div class="mfp-wrap"></div>

I have .lightbox-trigger that when clicked opens up .lightbox-content inside .mfp-wrap. By default, the .lightbox-content is hidden, and will only be visible once it is inside .mfp-wrap

When there is a YouTube video inside .lightbox-content.autoplay, I'd like for the video to autoplay once the video appears in .mfp-wrap.

I hope this makes sense. I tried this jQuery but it's not working for me...

$(".lightbox-trigger").click(function() { 
    $(".mfp-wrap .lightbox-content.autoplay iframe").attr("src").replace("?", "?autoplay=1&"); 
});

Solution

  • I was able to get this working using the following:

    // add parameter when opening video in popup
    $(".lightbox-trigger").on("click", function() { 
        $(".mfp-wrap .et_pb_video.autoplay iframe").each(function(){
            var addautoplay = $(this).attr("src")+"&autoplay=1";
            $(this).attr("src",addautoplay);
        });
    });
    
    //for removing the parameter when closing the video
    $('.lightbox-overlay').click(function() { 
        $(".et_pb_video.autoplay iframe").each(function(){
            var removeautoplay = $(this).attr("src").replace("&autoplay=1", "");
            $(this).attr("src",removeautoplay);
        });
        $.magnificPopup.close();
    });