Auto Embed Youtube Video

Hello, I am trying to embed my youtube video from my channel. But instead of embedding every time I have a new video I want it to autoplay the latest one. My link is: https://www.thenhans.com/

HTML CODE:
/*
[[x_video_embed][/x_video_embed]]
*/

and here is the JS:

var reqURL = “https://api.rss2json.com/v1/api.json?rss_url=” + encodeURIComponent(“https://www.youtube.com/feeds/videos.xml?channel_id=”);
function loadVideo(iframe){
$.getJSON( reqURL + iframe.getAttribute(‘id’),
function(data) {
var videoNumber = (iframe.getAttribute(‘vnum’)?Number(iframe.getAttribute(‘vnum’)):0);
console.log(videoNumber);
var link = data.items[videoNumber].link;
id = link.substr(link.indexOf("=") + 1);
iframe.setAttribute(“src”,“https://youtube.com/embed/”+id + “?controls=0&autoplay=1&mute=1”);
}
);
}
var iframes = document.getElementsByClassName(‘latestVideoEmbed’);
for (var i = 0, len = iframes.length; i < len; i++){
loadVideo(iframes[i]);
}

Thanks

Hi @codexworks,

Please add the following code to the text element(make sure you switch to HTML editor):

<iframe class="latestVideoEmbed" vnum='0' cid="UCAVNMyf1nt4yeRuZ9RNY5LQ" width="600" height="340" frameborder="0" allowfullscreen></iframe>

<script>
var reqURL = "https://api.rss2json.com/v1/api.json?rss_url=" + encodeURIComponent("https://www.youtube.com/feeds/videos.xml?channel_id=");
function loadVideo(iframe){
    jQuery.getJSON( reqURL + iframe.getAttribute('cid'),
      function(data) {
         var videoNumber = (iframe.getAttribute('vnum')?Number(iframe.getAttribute('vnum')):0);
        console.log(videoNumber);
         var link = data.items[videoNumber].link;
         id = link.substr(link.indexOf("=") + 1);  
         iframe.setAttribute("src","https://youtube.com/embed/"+id + "?controls=0&autoplay=1");
      }
   );
}
var iframes = document.getElementsByClassName('latestVideoEmbed');
for (var i = 0, len = iframes.length; i < len; i++){
       loadVideo(iframes[i]);
}
</script>

Hope that helps and thank you for understanding.

1 Like

Thank you so much. It works now. Awesome thai!

We are delighted to assist you with this.

Cheers!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.