Force embedded youtube video autoplay?

11,705

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).

Share:
11,705
Vincent Chua
Author by

Vincent Chua

Updated on June 04, 2022

Comments

  • Vincent Chua
    Vincent Chua almost 2 years

    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?