web hosting
build a website

Javascript click image to play video

Apr 5, 2013   //   by Anthony Devine   //   Website Development tips  //  Comments Off on Javascript click image to play video

If you want a still image to be displayed on your Webpage with a play button on it and then when that image is clicked it is replaced with a streaming video you can do it with the following code. I have added 2 examples 1 for Youtube and 1 for Vimeo.

Youtube

<div style="width:620px; height:377px;">
<script type="text/javascript" src="http://www.daemondesigns.co.uk/wp-content/uploads/2013/04/jquery-1.4.2.min_.js"></script> </p>
<div id="ytapiplayer2" style="display:none;">
<object width="620" height="377"><param name="movie" value="http://www.youtube.com/v/_0JXWplBsis?fs=1&hl=en_US&rel=0&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/_0JXWplBsis?fs=1&hl=en_US&rel=0&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="620" height="377"></embed></object></p>
</div>
<p><img src="http://www.daemondesigns.co.uk/wp-content/uploads/2013/04/Contact-Us-Image.jpg" id="imageID" /><br />
<script type="text/javascript">
$('#imageID').click(function() {
$('#ytapiplayer2').show();
$('#imageID').hide();
});
</script>
</div>
Vimeo
<div style="width:620px; height:377px;">
<script type="text/javascript" src="http://www.daemondesigns.co.uk/wp-content/uploads/2013/04/jquery-1.4.2.min_.js"></script></p>
<div id="ytapiplayer22" style="display:none;">
<iframe src="http://player.vimeo.com/video/21106256?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1" width="620" height="377" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>
</div>
<p><img src="http://www.daemondesigns.co.uk/wp-content/uploads/2013/04/iPad-Lifestyle-Play-Button.jpg" id="imageID2" alt=" " /><br />
<script type="text/javascript">
$('#imageID2').click(function() {
$('#ytapiplayer22').show();
$('#imageID2').hide();
});
</script>
</div>
If we look at the Vimeo example. The div id=”ytapiplayer22″(div with video in) is set to display=none to begin with, then the code gets the image id=”imageID2″(the still image) and says when that is clicked show the hidden div ytapiplayer22(which is the one the video is in) and hide the div id=”imageID2″(which is the still image). The video is set to autoplay by adding ;autoplay=1 onto the end of the code.

The Youtube example is exactly the same method except for the way the video is embedded in an object instead of an iframe.