Force embedded youtube video autoplay?

Vincent Chua picture Vincent Chua · Oct 21, 2013 · Viewed 11.3k times · Source

I know that we can autoplay the embed youtube video by adding the 'autoplay=1' parameter,

so if the embed link is like this

<iframe width="420" height="315" src="//www.youtube.com/embed/sorpTOyJXf8" frameborder="0" allowfullscreen></iframe>

then the with autoplay would look like this

<iframe width="420" height="315" src="//www.youtube.com/embed/sorpTOyJXf8?autoplay=1" frameborder="0" allowfullscreen></iframe>

but my concern is I have embedded quite a few youtube links in my site, it woulb be tedious to update the code one by one within the CMS, is there a javascript function that will enable youtube to autoplay globally?

Answer

m59 picture m59 · Jan 16, 2014

This is a simple solution. See the comments in the code for details on how it works:

//select the first iframe that has a src that links to youtube
var firstIframe = document.querySelector('iframe[src^="//www.youtube"]');

//get the current source
var src = firstIframe.src;

//update the src with "autoplay=1"
var newSrc = src+'?autoplay=1';

//change iframe's src
firstIframe.src = newSrc;

Live demo (click).