0

So I have a modal that displays a YouTube video. The problem is, when I close the modal, I still hear the video playing. I've looked at other solutions and they don't seem to work. Please keep in mind that I can't apply an ID to the iframe because the Iframe is created dynamically. Is there anyway to stop or pause the video using JavaScript or JQuery when I close the modal?

My code is below:

<script>
(function($){
  $(document).ready(function() {
  $('.b-close').on('click', function() {
   $('iframe').get(0).stopVideo();
  });
})(jQuery);
</script>



 <div id="element_to_pop_up" attrId="20">
   <a class="b-close">x</a>
   <h3 class="pop-hd">Title</h3>
   <div class="pretty-embed play" data-pe-videoid="nGSfaMxCu-U" data-pe-fitvids="true" data-pe-allow-fullscreen="false">

   <iframe width="330" height="186" style="border:none;" src="//www.youtube.com/embed/nGSfaMxCu-U?autoplay=1&amp;rel=1"></iframe>

   </div>

  </div>
Spanky
  • 699
  • 2
  • 11
  • 38

2 Answers2

0

You cannot control a video embedded in an iframe (not counting YouTube's own iframe, of course) if your code isn't running there.

The simplest solution to getting it to stop, though, is to simply remove the iframe altogether.

$('iframe').get(0).remove();

Presumably whatever mechanism put it there in the first place when opening the modal will put it back again if the visitor needs to reopen the same panel again.

VoteyDisciple
  • 37,319
  • 5
  • 97
  • 97
0

It's simple. Do following,

<iframe id="vidstop" width="100%" height="96%"
   src="">
   </iframe>  

btn.onclick = function() {
$("#vidstop").attr('src','https://www.youtube.com/embed/....');
}

and after click outside of iframe,

window.onclick = function(event) {
if (event.target == modal) {
    $("#vidstop").attr('src','');
}

}

Maulik
  • 349
  • 4
  • 19