Embedded YouTube video keep playing on closed container


I worked on a lightbox, a window opened by click an element over jquery.
Works well on pictures, but if i open a YouTube Video and play it, after close the window (display:none), the video keep playing in the background..
I used this tutorial for the lightbox.
The YouTube Video is embedded as iframe.

Close the window

    $(".js-modal-close, .modal-overlay").click(function() {
      $(".modal-box, .modal-overlay").fadeOut(500, function() {

How i can fix my problem ?


Step 1. enable the iframe API with enablejsapi=1 and add an id to the iframe:

<iframe id="player" src="https://www.youtube.com/embed/MxMBueIjtv0?enablejsapi=1" frameborder="0" allowfullscreen></iframe>

Step 2. load the API and create a player using the id from step 1. For this demo, I used player (probably a bad choice):

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
  /* probably should tie into the `onReady` event,
     but for this demo's purpose it's unnecessary.
     the video will probably be ready by the time
     you get to the close button. */
  player = new YT.Player('player');

Step 3. call the stopVideo Function in your close model snippet:

$(".js-modal-close, .modal-overlay").click(function() {
  player.stopVideo(); /* you can optionally also set the video back
                         at the beginning with `player.seekTo(0);` */
  $(".modal-box, .modal-overlay").fadeOut(500, function() {

Docs: https://developers.google.com/youtube/iframe_api_reference
Demo: http://jsfiddle.net/4f5dksj5/

Answered By – Joseph Marikle

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published