This is a bit of a repost, but none of the accepted answer uses the api in conjunction with JQuery events, if the do then the answer is incomplete. Past answer: Twitter Bootstrap Modal stop Youtube video
I wonder how to to get a Youtube Iframe to start playing automatically, when a bootstrap modal is opened through a link. The video should stop playing when the modal is dismissed. I looked at many of the answers, but none shows me a next to complete answer. So how do you use JQuery events from bootstrap (show.bs.modal
/hide.bs.modal
) to start/stop the video?
The following code works in Firefox if I press play on the video when the page(modal) first loads, then dismiss the modal and reopen it. This does not work in Safari or Chrome.
I looked at the documentation but can´t still get it to work: https://developers.google.com/youtube/iframe_api_reference
here is my code! html:
<div class="modal fade" id="video_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<iframe id="player" type="text/html" width="640" height="360" src="http://www.youtube.com/embed/zg8KE6bEP50?version=3&rel=0&enablejsapi=1&origin=*&html5=1" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div><!--/modal fade-->
Javascript:
jQuery( document ).ready(function() {
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
});
var player;
window.onYouTubePlayerAPIReady = function() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
$("video_modal").on('shown.bs.modal', function() {
player.playVideo();
});
$("video_modal").on('hidden.bs.modal', function() {
player.stopVideo();
});
}