Jibes Jibes - 11 months ago 75
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 Source

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) {
//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

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