Skip to main content Accessibility Feedback

Stopping YouTube, Vimeo, and HTML5 Videos with JavaScript

One annoying thing about a few of my content-oriented scripts (like Slider, Tabby, and Modals) is that if they contained a video, it would continue to play even when the slider was slid, the tab was toggled or the modal was closed.

Well, no more!

Stopping videos with JavaScript #

Those scripts have all been updated with a new function that stops or pauses YouTube, Vimeo and HTML5 videos when the content area is closed. If you’re interested in adding something like that to your scripts, here’s how it works.

Add this method to your script:

var stopVideo = function ( element ) {
    var iframe = element.querySelector( 'iframe');
    var video = element.querySelector( 'video' );
    if ( iframe !== null ) {
        var iframeSrc = iframe.src;
        iframe.src = iframeSrc;
    if ( video !== null ) {

Call the function as needed, passing the container element into the function:

stopVideo( tab );

This works in all modern browsers, and Internet Explorer 8 and above.

🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips