As mentioned in this question: iframe Video in Modal Popup Replays Audio After Modal Close - Wordpress Site, I am using the Impreza Wordpress theme. To a page on my site, I added a popup modal element which contains an embedded iframe YouTube video. When I added ?autoplay=1 to the iframe src url, the video autoplays as expected when I opened the modal popup, but when I closed the modal popup, the audio replays even though the modal popup and video are no longer open/visible.
Here's the HTML I put in the popup modal element (Stack Overflow video for example purposes):
<div class="responsive-video">
<iframe class="myEmbed" title="YouTube video player" src="https://www.youtube.com/embed/HJtJXMKpl2g?autoplay=1" allowfullscreen="allowfullscreen" width="1024" height="565" frameborder="0"></iframe>
</div>
And here's the JS solution I came up with:
jQuery(document).ready(function($) {
var video = $(".responsive-video iframe").attr("src");
video = video.replace("?autoplay=1", "");
document.onkeydown = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key === "Escape" || evt.key === "Esc");
} else {
isEscape = (evt.keyCode === 27);
}
if (isEscape) {
$(".responsive-video iframe").attr("src","");
$(".responsive-video iframe").attr("src",video);
}
};
$('.w-popup-wrap').click(function(e) {
e.preventDefault();
$(".responsive-video iframe").attr("src","");
$(".responsive-video iframe").attr("src",video);
console.log(video);
});
});
The .w-popup-wrap class refers to the div created by the theme that contains the div with the class .responsive-video that I created.
The issue I'm having now is this: I now have two modal popups on my page, each with an iframe containing a different video, like this:
<div class="responsive-video">
<iframe class="myEmbed" title="YouTube video player" src="https://www.youtube.com/embed/HJtJXMKpl2g?autoplay=1" allowfullscreen="allowfullscreen" width="1024" height="565" frameborder="0"></iframe>
</div>
<div class="responsive-video">
<iframe class="myEmbed" title="YouTube video player" src="https://www.youtube.com/embed/6XtwS2Ju76Y?autoplay=1" allowfullscreen="allowfullscreen" width="1024" height="565" frameborder="0"></iframe>
</div>
The first video behaves as expected: When I open it, it autoplays and when I close it it stops. However, if I then open the second video, the FIRST video loads in the second modal and does not autoplay. If I reload the page and open the second video, it also behaves as expected and autoplays on open, closes on stop. But if I open it again, once again the first video loads in the modal.
I understand that I need to check each YouTube iframe for its src url and then replace autoplay with an empty string when the modal closes, but I'm having trouble figuring out how to accomplish that when there's multiple videos on the page. Any solutions would be much appreciated!