Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Last active April 19, 2026 05:35
Show Gist options
  • Select an option

  • Save cferdinandi/9044694 to your computer and use it in GitHub Desktop.

Select an option

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();
}
};
@donluismx

Copy link
Copy Markdown

It worked great.
Additionally I used it inside a pair of JQuery events (a modal close close button click and on the background overlay click).

@gostak-dd

Copy link
Copy Markdown

@Luminicus This outta do it.

/**
 * Stop all iframes or HTML5 <video>'s from playing
 */
var stopVideos = function () {
	var videos = document.querySelectorAll('iframe, video');
	Array.prototype.forEach.call(videos, function (video) {
		if (video.tagName.toLowerCase() === 'video') {
			video.pause();
		} else {
			var src = video.src;
			video.src = src;
		}
	});
};

Thanks man!

@vistree

vistree commented May 10, 2023

Copy link
Copy Markdown

Hi all, is there a way to call the function when a YouTube or Vimeo or HTML5 video is clicked to play?

@Fezzito

Fezzito commented Jul 26, 2023

Copy link
Copy Markdown

i tried the two answers and this turnt out to be the best one, in the first one you might enconter the problem of " var iframe = element.querySelector( 'iframe'); is not a function", dont know if it was because of my tsconfig or what.
Also, if you must call the function in several components (wich is my case) you should consider switching var stopVideos to const stopVideos an all the following var to let to avoid scope problems

that being said, amazing approach man, well done

@filipsjostrand

Copy link
Copy Markdown

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
Copy Markdown

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

@robweychert

Copy link
Copy Markdown

Super useful, thanks! In my implementation, I added a .replace() to line 10 in case of autoplay:

iframe.src = iframeSrc.replace("?autoplay=1", "");

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