start/play embedded (iframe) youtube-video on click of an image
Solution 1:
The quick and dirty way is to simply swap out the iframe
with one that has autoplay=1
set using jQuery.
THE HTML
Placeholder:
<div id="videoContainer">
<iframe width="450" height="283" src="https://www.youtube.com/embed/VIDEO_ID_HERE?wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>
</div>
Autoplay link:
<a class="introVid" href="#video">Watch the video</a></p>
THE JQUERY
The onClick
catcher that calls the function
jQuery('a.introVid').click(function(){
autoPlayVideo('VIDEO_ID_HERE','450','283');
});
The function
/*--------------------------------
Swap video with autoplay video
---------------------------------*/
function autoPlayVideo(vcode, width, height){
"use strict";
$("#videoContainer").html('<iframe width="'+width+'" height="'+height+'" src="https://www.youtube.com/embed/'+vcode+'?autoplay=1&loop=1&rel=0&wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>');
}
Solution 2:
You can do this simply like this
$('#image_id').click(function() {
$("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1');
});
where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.
Solution 3:
To start video
var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);
To stop video
var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);
You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters
works for both vimeo and youtube on FF & Chrome
Solution 4:
Example youtube iframe
<iframe id="video" src="https://www.youtube.com/embed/xNM7jEHgzg4" frameborder="0"></iframe>
The click to play HTML element
<div class="videoplay">Play</div>
jQuery code to play the Video
$('.videoplay').on('click', function() {
$("#video")[0].src += "?autoplay=1";
});
Thanks to https://codepen.io/martinwolf/pen/dyLAC