Embedding multiple videos on a webpage without overlapping playback
When embedding multiple videos on a single webpage, you may encounter a problem where one video continues playing after starting another. The same can happen when using modals — if you click “next” or “previous,” the previous video may continue to play in the background.
You can prevent this by adding a script to stop all embedded videos when switching content.
Example Script
function stopPlayingEmbedVideo() {
// Set the scope to a region where to look for iframes
// otherwise set scope as the entire document
// var myScope = document;
// if there is an iframe inside maybe embedded multimedia video/audio, we should reload so it stops playing
/*
* var videoContainer = a div with id #container.
* You can rename container id name to any other wrapper div
* This is the region where the script looks for all the iframes
*/
var videoContainer = document.getElementById('container');
var iframes = videoContainer.getElementsByTagName("iframe");
if (iframes != null) {
for (var i = 0; i < iframes.length; i++) {
iframes[i].src = iframes[i].src;
}
}
}
/*
* var button = a button with id #stop-playing-btn.
* You can rename stop-playing-btn to any other id name
* This is the button that fires the event to stop playing video
* You can assign this event to modal closing, next prev for example
*/
var button = document.getElementById('stop-playing-btn');
button.addEventListener("click", stopPlayingEmbedVideo);
Example HTML Structure
<div id="container">
<iframe scrolling="no" frameborder="0" src="example/iframe" width="600" height="400" allowFullScreen="true"></iframe>
<iframe scrolling="no" frameborder="0" src="example/iframe" width="600" height="400" allowFullScreen="true"></iframe>
</div>
<button id="stop-playing-btn">Stop playing</button>
You can assign the stopPlayingEmbedVideo() function to any event — for example, clicking a prev/next button in a modal, or when the modal closes.