Tim
Tim

Reputation: 2649

Javascript to replace IMG with YouTube video - Autoplay not working as it should

I've got an image where when you click it, it gets hidden and the YouTube video gets shown.

I wanted the video to play when you click the image so I have set a parameter on the YT link so it autoplays and this works fine in every browser tested apart from Google Chrome.

Any ideas on why Chrome is autoplaying the video before I've even clicked the image?

 <div id="youtube" style="display:none;">
 <iframe width="940" height="520" src="http://www.youtube.com/embed/kr-oMG6EYSs?rel=0&showinfo=0&autoplay=1" wmode="transparent" frameborder="0" allowfullscreen></iframe>
 </div>


 <img src="images/slider_worklife_top.jpg" width="942" height="521" id="imageID" />
 <script type="text/javascript">
 $('#imageID').click(function() {
 $('#youtube').show();
 $('#imageID').hide();
 });
 </script>

Upvotes: 0

Views: 4104

Answers (2)

Pier Paolo Ramon
Pier Paolo Ramon

Reputation: 2900

The embed source is configured to autoplay, hiding the container div does nothing (at least in theory, probably browsers different than Chrome do not permit the iframe to execute).

The solution is to remove completely the iframe from the page, and appending it to the page inside the container when you need it.

var yt = $('#youtube');

// If you cant store the html directly
var ythtml = yt.html();
yt.hide().children().remove();

// load iframe once needed
$('#imageID').click(function(){
  $(this).hide();
  yt.html(ythtml).show();
});

Of course there is a real solution: using YT's APIs.

Upvotes: 0

avall
avall

Reputation: 2055

Try to wrap your JS code with $(function(){ /* CODE */ }

IF it doesn't help just try something different and don't waste your time :) :

<div id="youtube" style="display:none;">
   <iframe width="940" height="520" src="" wmode="transparent" frameborder="0" allowfullscreen></iframe>
 </div>

<img src="images/slider_worklife_top.jpg" width="942" height="521" id="imageID" />
<script type="text/javascript">
$(function(){
  $('#imageID').click(function() {
    $('#youtube').show().find("iframe").attr("src","http://www.youtube.com/embed/kr-oMG6EYSs?rel=0&showinfo=0&autoplay=1");
    $('#imageID').hide();
  });
});
</script>

Upvotes: 3

Related Questions