Recently I worked on a project that required the placement of multiple videos on a page. The requirements called for each video to open and play embedded in a Bootstrap modal. That's not difficult to accomplish, right? Well it's not, except that when a video is playing in a Bootstrap modal and you close the modal, the video continues playing. You don't see it, but you can hear it. And if you open one of the other videos on the page and start playing it, you now have two videos playing at the same time. Not a very good user experience to say the least.

So here's what I did to stop video playback whenever the Bootstrap modal is closed. All it takes is a bit of jQuery JavaScript:

Let's say we have a couple of videos on a page, each inside a modal, like so (for brevity, not all the modal markup is shown):

<div class="modal"...>
    ...
    <div class="modal-body">
        <video class="video-player" controls poster="/path/to/poster/image/file_1/">
            <source src="/path/to/video/file_1" type="video/mp4">
        </video>
    </div>
</div>

<div class="modal"...>
    ...
    <div class="modal-body">
        <video class="video-player" controls poster="/path/to/poster/image/file_2/">
            <source src="/path/to/video/file_2" type="video/mp4">
        </video>
    </div>
</div>

The following script will loop through all video containers to "stop" video playback when the modal becomes hidden. It actually resets playback on each video by loading it:

    ...
    <script>
        // Stop video when modal becomes hidden (either by clicking on
        // close button or clicking outside of the modal area).
        $(".modal").on("hidden.bs.modal", function () {
            var videosOnPage = $('video').length;

            for (i = 0; i < videosOnPage; i++) {
                $(".video-player")[i].load();
            }

            return false;
        })
    </script>
</body>

That's it. Happy coding!