Rui Costa Rui Costa - 3 months ago 16
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.

Why?

JSFIDDLE: https://jsfiddle.net/u19ut5gt/6/

HTML

<div id="fw16-liam">
<div class="fw16-button playvideo">Play Video</div>
<div id="liam-video"><div id="ytplayer"></div></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>


Javascript

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

if(document.getElementById('iframe_api') === null){
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
tag.id = "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(event.data === YT.PlayerState.ENDED){
event.target.playVideo();
}

// If user, pause video, then this hide.
if(event.data == 2){
event.target.stopVideo();
$("#liam-video").fadeOut(200);
}
}
}
});
}


CSS

.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;}

Answer

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) {
    player.playVideo();
    return player;
  }
  player = new YT.Player('ytplayer', {
    ...
  }
}

Checkout this fiddle.

Comments