Andreas Eracleous

Twitter Bootstrap Modal stop Youtube video

To stay updated when a new content for devs is out, sign up!

I worked on a Bootstrap project, where I had to implement Youtube video on Twitter Bootstrap Modal component. when I pressed to open the Modal component for playing the video, I noticed something weird on it since after Bootstrap Modal has closed. I realised that the Youtube video has continue playing on the background even when it was closed. I had tried many ways to fix it but at the end I found a solution with JavaScript on how I can stop a Youtube video to still playing on the background and below you can see my solution.

JavaScript Code for Twitter Bootstrap Modal stop Youtube video

I used the Modal event function “ hidden.bs.modal ” as they mentioned in their documentation in which it starts to execute when the modal has finished being hidden from the user. What I did I remove and set the video URL in iFrame again when it has been closed the Modal. In this way it terminate the procedure of the video as a result to make it to stop.

  $('#youtubeVideo').on('hidden.bs.modal', function() {
  var $this = $(this).find('iframe'),
    tempSrc = $this.attr('src');
  $this.attr('src', "");
  $this.attr('src', tempSrc);
}); 

JavaScript Code for Twitter Bootstrap Modal stop HTML5 video

  $('#html5Video').on('hidden.bs.modal', function() {
  var html5Video = document.getElementById("htmlVideo");
  if (html5Video != null) {
    html5Video.pause();
    html5Video.currentTime = 0;
  }
}); 

See the Pen Twitter Bootstrap Modal stop Youtube video by Andreas Eracleous ( @Sp00ky ) on CodePen .