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.
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):
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:
Notice the variable
videosOnPage must equal the number of videos on the page.
That’s it. Happy coding!