Site icon WebDevStudios

How To: Stop a YouTube Video from Playing when Closing a Lightbox Modal

If you’ve ever had a YouTube video continue to play after closing the lightbox it was displayed in, you know it can be a very annoying bug to fix. The below code snippet will fix this issue. This method applies to the facebox script but can easily be applied to just about any lightbox modal that has an event to attach to when closing the modal.

// We're binding to the 'afterClose' event that facebox
// fires when closing a lightbox instance
jQuery(document).bind('afterClose.facebox', function() {
  // target iframes with src attribute containing 'youtube'
  // (within the facebox-generated .popup wrapper).
  var vid = jQuery('.popup iframe[src*="youtube"]');
  // if such an element exists
  if ( vid.length > 0 ){
    // get iframe's src attribute and cache it to a variable
    var src = vid.attr('src');
    // empty the iframe's src attribute
    // (this will kill the video playing)
    vid.attr('src', '');
    // and restore the iframe src url, ready to be played
    // again when the lightbox is displayed
    vid.attr('src', src);
  }
});
Exit mobile version