Skip to main content

Stopping Embedded YouTube Videos with JavaScript in 2025

 It's easy to embed a YouTube video on your web page by inserting something like this into the HTML:

<div class="youtube_responsive"><iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" src="https://www.youtube.com/embed/amgybZEP-TI?enablejsapi=1" title="YouTube video player"></iframe></div>

What's more tricky is doing things with it once it's there. For example, you might want it to start playing automatically and if you Google, you'll find lots of (mainly) old stuff about how to do it. Unfortunately, those techniques don't work any more because YouTube "depreciated" them.

That's why the title of this post about stopping a video playing says "in 2025" because it may become out of date - although my technique is quite brutal and I'm not sure that YouTube will be able to "depreciate" it successfully :-)

The basic idea is to completely wipe out the embedded code using  JavaScript. 

1. In the HTML, put the embed code inside a <div> of your own, like this

<div class="panel"><div class="youtube_responsive"><iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" src="https://www.youtube.com/embed/amgybZEP-TI" title="YouTube video player"></iframe></div></div>

2. In the JavaScript, find the panel you want to stop playing and set its innerHTML to ""

var panels = document.getElementsByClassName("panel"); to_stop = panels[3]; //this selects the fourth panel to_stop.innerHTML = "";

That's the essence of the technique but for the curious, some notes on why I wanted to do this and a few complications

Why

I had a page of many embedded videos and users could easily have several playing at once with annoying overlapping sound tracks. It also took a long time loading thumbnails of all the videos. So I put each video in a "fold" of an accordion and made it so that only one fold could be open at a time but videos in closed folds carried on playing. So I fixed that with this technique and the finished page - which might change in time - is here

More Detail

Setting the innerHTML like this to nothing at all removes it from the page. "permanently" but if you need to see it and play it again without refreshing the page,  save a copy somewhere and reload it into innerHTML when you need it again.

Even More

  • It's worth knowing that Google doesn't really like pages with multiple videos and often will only index the first one on the page at best. So, I wrote some code to separate out the videos onto individual pages automatically. You can see the finished result here
  • I've also written an article on Making Dance Videos

Comments