Stop videos embedded in your HTML script using JS

Manisha Sharma
2 min readApr 28, 2019

--

Here’s a simple solution to a very common issue faced when one embeds a native or 3rd party video in content oriented scripts such as sliders, tabs/icon tabs and modals — if you play the video and choose to collapse/slide or toggle or close the containing tag (slider/tab/modal), the video would continue to play.

I saw many solutions on stack exchange that would require you to modify the src of the element containing and call postMessage function. Well, all of that is an overkill for such a simple problem.

The following snippet will allow you to stop videos embedded in your HTML script, whether they are native to your website (in video tag) or embedded from 3rd party (Youtube, Vimeo, DailyMotion, etc) as an iframe and works in all modern browsers in addition to Internet Explorer 8 and above :-

let videoStopper = function(id) {
let containerElement = document.getElementById(id);
let iframe_tag = containerElement.querySelector( 'iframe');
let video_tag = containerElement.querySelector( 'video' );
if ( iframe_tag) {
let iframeSrc = iframe_tag.src;
iframe_tag.src = iframeSrc;
}
if ( video_tag) {
video_tag.pause();
}

So all we are actually doing in the above snippet is reassigning the video source url to the iframe or video tag (in case of native videos embedded), and this will stop the video. We do so by getting a reference of the id of the element that contains the video or iframe tag in which the video is embedded.

Next step is to call this videoStopper function in the function that is triggered on sliding/collapsing/toggling/closing the parent element — the element in which the video/iframe tag rests, as illustrated below:

HTML:<div id="videoContainer">
<iframe width="560" height="315" src="https://www.youtube.com/embed/TJ8TnlfzF4Q" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
</iframe>
</div>
JS:
someFunction(){ //this helps close the parent element
videoStopper("videoContainer"); //this will stop the video
}

Hope it helps! :)

--

--

Manisha Sharma

Javascript Enthusiast and Senior Software Engineer at Freshworks