Charlie Wedel
Charlie Wedel

Reputation: 79

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&"); 
});

Upvotes: 0

Views: 2502

Answers (2)

Charlie Wedel
Charlie Wedel

Reputation: 79

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();
});

Upvotes: 1

Dhana
Dhana

Reputation: 1658

Youtube video embed link - Add property

allow="autoplay; encrypted-media";

Sample iFrame Link:

<iframe width="560" height="315" src="https://www.youtube.com/embed/iVe__Py2GuU" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Example:

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

Upvotes: 1

Related Questions