Step 1: To start, enable the iframe API by adding enablejsapi=1
to the iframe URL and assigning an id
to the iframe element:
<iframe id="video-player" src="https://www.youtube.com/embed/MxMBueIjtv0?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
Step 2: Next, load the API script and create a player using the id specified in step 1. In this example, we used video-player
:
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() {
/* Additional actions can be taken on the 'onReady' event,
but for the purpose of this demo, it's not necessary.
The video should be ready by the time you close the modal. */
player = new YT.Player('video-player');
}
Step 3: Lastly, utilize the stopVideo
function in your close modal snippet:
$(".js-modal-close, .modal-overlay").click(function() {
player.stopVideo(); /* Optionally, you can set the video to start at 0 with `player.seekTo(0);` */
$(".modal-box, .modal-overlay").fadeOut(500, function() {
$(".modal-overlay").remove();
});
});
More information: https://developers.google.com/youtube/iframe_api_reference
Demo: http://jsfiddle.net/4f5dksj5/