user2265915 user2265915 - 1 year ago 104
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.


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

HTML (curly braces denote data pulled from CMS):

<a href="#" title="Watch Video" data-toggle="modal" data-target="#panelModal-{count}">
<div class="video-background" style="background-image:url({video_youtube_id}/hqdefault.jpg)"></div>
<div class="video-details">
<!-- 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 class="modal-body">
<div id="yt-player-{count}" class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="{video_youtube_id}?enablejsapi=1"></iframe>

The AJAX part is this:

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

$('.sub-nav a').removeClass('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

// Fade-in our new content

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

Answer Source

you can use following jQuery command.


If your using Player API :

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