Question

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!!!

Was it helpful?

Solution

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>

OTHER TIPS

Easier way to play youtube videos -

$("iframe")[0].contentWindow.postMessage("{\"event\":\"command\",\"func\":\"playVideo\",\"args\":\"\"}", "*");

Make sure that the iframe has loaded $(window).load(function () { and to add &amp;enablejsapi=1 to the url.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top