How to Stop a YouTube Video from Playing after Lightbox Closes

Say you have a modal window, commonly referred to as a lightbox, that opens when you click a button and allows the user to play a video.

You also have a close button that will allow the user to close the window. Something like this:

screenshot of a modal window with a vimeo video inside and a close button, the rest of the web page is greyed out

View the Demo

So we’re using jQuery to show and hide the modal window. The issue is, when you click the little X to close the window, the video will continue to play in the background. Even though it’s hidden, the content in the iframe is still rolling. Of course we want the video to stop playing, here’s how we do it with jQuery.

<script>
jQuery(document).ready(function($) {
$(function(){
//Snag the URL of the iframe so we can use it later
var url = $('.video-container iframe').attr('src');
$('p.video-button a').click(function() {
$('.video-container').show();
//Below we remove the URL to stop the video from playing, here we add it back in
$('.video-container iframe').attr('src', url);
});
$('p.close-video a').click(function() {
$('.video-container').hide();
//Assign the iframe's src to null, which kills the video
$('.video-container iframe').attr('src', '');
});
});
});
</script>

View the demo linked above for the complete CSS, HTML and jQuery.

Up Next: Fooling with SEO: A Cautionary Tale