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() {
$(".modal-overlay").remove();
});
});
Docs: https://developers.google.com/youtube/iframe_api_reference
Demo: http://jsfiddle.net/4f5dksj5/