user2265915 user2265915 - 3 months ago 23
Ajax Question

Stop YouTube video on modal close - after AJAX load

I have a small script that stops YouTube videos from playing after their modals are closed. The issue is it doesn't work if the HTML has been loaded via AJAX.

Script:

$('#panelModal-1').on('hidden.bs.modal', function () {
callPlayer('yt-player-1', 'stopVideo');
});
$('#panelModal-2').on('hidden.bs.modal', function () {
callPlayer('yt-player-2', 'stopVideo');
});


HTML (curly braces denote data pulled from CMS):

<li>
<a href="#" title="Watch Video" data-toggle="modal" data-target="#panelModal-{count}">
<div class="video-background" style="background-image:url(http://img.youtube.com/vi/{video_youtube_id}/hqdefault.jpg)"></div>
<div class="video-details">
<h4>{title}</h4>
<p>{video_subtitle}</p>
</div>
</a>
<!-- Modal -->
<div class="modal fade" id="panelModal-{count}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel-{count}">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel-{count}">{title}</h4>
</div>
<div class="modal-body">
<div id="yt-player-{count}" class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/{video_youtube_id}?enablejsapi=1"></iframe>
</div>
</div>
</div>
</div>
</div>
</li>


The AJAX part is this:

$(document).ready(function()
{
$('.sub-nav').delegate('.load-case-studies', 'click', function(e)
{
// Don't follow the link
e.preventDefault();

$('.sub-nav a').removeClass('active');
$(this).addClass('active');

// Fetch the next page
$.get($(this).attr('href'), function(data)
{
// Only grab the part of the page we want
content = $(data).find('.ajax-wrapper').hide();

// Add it to the DOM
$(content).replaceAll('#entry-container');

// Fade-in our new content
$(content).fadeIn('fast');
});
});
});


How can I get the videos to stop playing after the modal is closed, if the data has been loaded via AJAX?

Answer

you can use following jQuery command.

$('#playerID').get(0).stopVideo();

If your using Player API :

var player = new YT.Player('player');    
player.stopVideo();