Search code examples
javascripthtml5-videobootstrap-modal

Video still playing when bootstrap modal closes


Modal window is closed, but the video keeps playing. I want to stop video when the modal window is closed.

I tried different ways, with a YouTube video and Vimeo it's work, but it's doesn't with MP4.

$(document).ready(function() {
  var $videoSrc;
  $(".video-btn").click(function() {
$videoSrc = $(this).data("src");
  });
  console.log($videoSrc);
  $("#myModal").on("shown.bs.modal", function(e) {
$("#video").attr(
  "src",
  $videoSrc + "?autoplay=1&modestbranding=1&showinfo=0"
);
  });
  $("#myModal").on("hide.bs.modal", function(e) {
   $("#video").attr("src", $videoSrc);
  });
});
<html>
<head>
link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <img src="https://tinyjpg.com/images/social/website.jpg?v=1&quality=80&format=jpeg" class="video-btn" data-toggle="modal" data-src="https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4"  data-target="#myModal">

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <!-- 16:9 aspect ratio -->
                    <div class="embed-responsive embed-responsive-16by9">
                        <iframe class="embed-responsive-item" src="" id="video"   allow="autoplay"></iframe>
                    </div>
                </div>
</body>
</html>


Solution

  • When you close the model, it does not call the player to stop playing the video. You can you add onclick="javascript::player.api('pause')" in your model close button.

    <button type="button" onclick="javascript::player.api('pause')" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button
    

    It should resolve your issue.