Jibes Jibes - 3 months ago 22
Javascript Question

youtube embed autoplay on page anchor link click

I have a youtube clip embedded at the bottom of a page, with an anchor link at the top that scrolls to it when clicked.

Is it possible to autoplay the embedded youtube clip when the anchor link is clicked?

Could I use jQuery to do some kind of on click function of the anchor link, autoplay youtube embed?

Any pointers are highly appreciated!
Thank you!!!

Answer

You need to use the youtube API to do this. Here is a plunker to demonstrate: http://plnkr.co/edit/lYCJeQBj0Cjl0FuzKTfE?p=preview

var player;
function onYouTubeIframeAPIReady() {
  //this is the id of your video
  player = new YT.Player('your-video');
}
//call this function from your links onclick
function playVideo() {
  if(player) {
    player.playVideo();
  }
}
//this loads the youtube api
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


//iframe embed markup, note the enablejsapi=1 portion of the video URL
<iframe 
   id="your-video" 
   width="420" 
   height="315" 
   src="//www.youtube.com/embed/6yEgcb167k4?enablejsapi=1" 
   frameborder="0" 
   allowfullscreen
>
</iframe>

//your button markup
<a href="#your-video" onclick="playVideo()">Go to video</a>