Home > Net >  How to pause the video when popup is closed in bootstrap?
How to pause the video when popup is closed in bootstrap?

Time:02-27

I am using Bootstrap 5 Modal Popup, I embedded an Iframe in the popup box and everything is working fine but the thing is that When I am closing the Popup the video is not stoping/pausing and even the Popup is closed it is still Running in the background and I tried to stop it via Jquery but don't know why it is not working. So can anyone please tell me how to pause/stop the video when the popup is closed?

$(document).ready(function() {
  var url = $("#how-it-works-video").attr('src');

  $("#exampleModal").on('hide', function() {
    $("#how-it-works-video").attr('src', '');
  });

  $("#exampleModal").on('show', function() {
    $("#how-it-works-video").attr('src', url);
  });
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>





<!-- Button trigger modal -->
<a  type="button" data-bs-toggle="modal" data-bs-target="#exampleModal">
  How it works
</a>

<!-- Modal -->
<div  id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">

  <div >
    <div >
      <div >
        <h5  id="staticBackdropLabel">Modal title</h5>
        <button type="button"  data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      
      
      <div >      
      <iframe id="how-it-works-video" width="100%" height="100%" src="https://www.youtube.com/embed/BrD3abCyuzw" title="YouTube video player" frameborder="5" allowfullscreen></iframe>
      </div>


    </div>
  </div>
</div>


<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg OMhuP IlRH9sENBO0LRn5q 8nbTov4 1p" crossorigin="anonymous"></script>

Edit: I noticed the video is not playing in Stackoverflow Code editor but if you use any other code editor it will work

CodePudding user response:

Bootstrap v5 have different event listeners. You have to change show to shown.bs.modal / hide to hide.bs.modal.

  $("#exampleModal").on('hide.bs.modal', function() {
    $("#how-it-works-video").attr('src', '');
        console.log('Unloaded')
  });

  $("#exampleModal").on('shown.bs.modal', function() {
    $("#how-it-works-video").attr('src', url);
        console.log('Loaded')
  });

https://jsfiddle.net/39gmbk6p/

  • Related