Rui Costa Rui Costa - 6 months ago 31
jQuery Question

Youtube Iframe API only works at the first

I've tried some solutions presented here by without success.

Youtube video is inside hidden div.

Click on button and video appears, but when i click on Pause button, the div need to hidden again (mandatory and working)

At the second time, i click on Play Video button, video appears but neither autoplay neither pause are triggering the hide events.




<div id="fw16-liam">
<div class="fw16-button playvideo">Play Video</div>
<div id="liam-video"><div id="ytplayer"></div></div>
<script src=""></script>


$("#fw16-liam .playvideo").click(function(){
runPlayer( '0m9hYRUV920' );

if(document.getElementById('iframe_api') === null){
var tag = document.createElement('script');
tag.src = ""; = "iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

function runPlayer( video_id ){
var player;
player = new YT.Player('ytplayer', {
playerVars: {
autoplay: 1,
html5: 1,
controls: 1,
showsearch: 0,
showinfo: 0,
loop: 1,
fs: 0
height: '300',
width: '487',
videoId: video_id,
events: {
onStateChange: function (event) {
// Loop after video end
if( === YT.PlayerState.ENDED){;

// If user, pause video, then this hide.
if( == 2){;


.playvideo{width:112px; height: 37px; color: white;}
.fw16-button {cursor: pointer;cursor: hand; background-color: red;}
#liam-video{display:none; background: #9e7969; width: 487px; height:677px; position: relative; left: 0px; top: 20px; border: none;}
#liam-video iframe{border:none;}


You should initialize player only once. The next time you need to reproduce the video, just call playVideo. In your runPlayer function, try something like this:

var player;
function runPlayer( video_id ){
  if(player) {
    return player;
  player = new YT.Player('ytplayer', {

Checkout this fiddle.