In a recent project I had to show and autoplay an embedded YouTube video on click of a button. My first reaction was to use the YouTube API, create the video on the fly with Javascript and have some functions at my finger tips to start the video and so on. But then I started to look around if it might be possible to do the same with the normal embedded iframe code and I did find something that is much easier than to do all this YouTube API stuff.
So if you just need to play the video on click and don't need to know when it's ended or do other things with it, that the YouTube API allows you to do, this is the solution you are looking for:
First we need a simple link and the iframe Embed Code.
<a id="play-video" href="#">Play Video</a>
<iframe id="video" width="420" height="315" src="//www.youtube.com/embed/9B7te184ZpQ?rel=0" frameborder="0" allowfullscreen></iframe>
And then we write some simple jQuery, which on click just extends the YouTube video source with the autoplay parameter thus plays the video. I also prevent the link from behaving like it normally would. Simple as that.
$(document).ready(function() {
$('#play-video').on('click', function(ev) {
$("#video")[0].src += "&autoplay=1";
ev.preventDefault();
});
});
Maybe this is useful for some of you in the future. :) I also made a CodePen so you can see the code in action.