Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Last active October 8, 2024 13:22
Show Gist options
  • Save cferdinandi/9044694 to your computer and use it in GitHub Desktop.
Save cferdinandi/9044694 to your computer and use it in GitHub Desktop.
A simple method to stop YouTube, Vimeo, and HTML5 videos from playing.
/**
* Stop an iframe or HTML5 <video> from playing
* @param {Element} element The element that contains the video
*/
var stopVideo = function ( element ) {
var iframe = element.querySelector( 'iframe');
var video = element.querySelector( 'video' );
if ( iframe ) {
var iframeSrc = iframe.src;
iframe.src = iframeSrc;
}
if ( video ) {
video.pause();
}
};
@filipsjostrand
Copy link

My updated version to stop all videos on page:

const stopVideos = () => {
  document.querySelectorAll('iframe').forEach(v => { v.src = v.src });
  document.querySelectorAll('video').forEach(v => { v.pause() });
};

(I couldn't use the YouTube postMessage one because some of my YT videos were displayed in a nested iframe via embed.ly)

Excellent! Thumbs up! d.,.b

@bachoo786
Copy link

does this stop the related videos from showing on a live youtube stream playing on video js player?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment