Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

play iframe video on click a link javascript

I have used a iframe video in my web page. This is my html code

<iframe id="video1" width="520" height="360" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
<a href="#" id="playvideo">Play video</a>

I need to play video onclick the play video link. How can i do that?

like image 519
Sam Hanson Avatar asked Nov 29 '12 04:11

Sam Hanson


1 Answers

This works, it appends autoplay=1 to the url causing the video to start playing.

addendum: If your video's source does not already have a querystring then it would be prudent to add a ? instead of a &, as is sometimes the case. This can be done by looking for its existence.

<iframe id="video1" width="520" height="360" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
<a href="#" id="playvideo">Play video</a>
<script>
 //use .one to ensure this only happens once
 $("#playvideo").one(function(){
  //as noted in addendum, check for querystring exitence
  var symbol = $("#video1")[0].src.indexOf("?") > -1 ? "&" : "?";
  //modify source to autoplay and start video
  $("#video1")[0].src += symbol + "autoplay=1";
 });
</script>

However, most people inherently understand that if they want a video to play, they will just click on it and I would suggest just leaving that to them or starting the video off with autoplay.

Also need to mention that autoplay does not work on mobile devices (powered by Android or iOS)

like image 166
Travis J Avatar answered Oct 04 '22 20:10

Travis J