Reputation: 369
I am using this script to fadeIn and autoplay YouTube video upon clicking on button and automatically fade it out when the video finishes playing (plus it's also supposed to scroll from the top by 90px). The script works perfectly in Safari and Chrome, however in Firefox 3.6 it fadesIn the video but doesn't automatically play it - the user has to click the play button on the player, and the scrollTop isn't working for some reason. And in Internet Explorer 8 is the same problem as in Firefox, but the video won't even fadeOut when finishes playing.
Any idea what could be the problem please and how could I fix it? Thanks a lot, any help is very much appreciated.
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('vid', {
height: '539',
width: '958',
videoId: 'wgDQoA7cqsQ',
events: {
'onStateChange': onPlayerStateChange
}
});
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
$("#vid").fadeOut(500);
}
}
function startVideo() {
$("#vid").fadeIn(2000);
player.playVideo();
$("html, body").animate({ scrollTop: 90 }, 600); return false;
};
</script>
Upvotes: 1
Views: 1804
Reputation: 90
I think in some browsers the video player is not ready to reproduce the video, but you can attach an event to know when the api is ready to play the video (onReady event), this is done by adding the event in the constructor. Then when the builder told you that you are ready, there you can reproduce your video. About the scroll problem, is likely the video player has not being initialized yet, so there is no playVideo function and that's why the animation does not scroll up, because your code breaks.
I have also noticed is some browsers that the container with a display:none property doesn't behave very well, in order to solve this I have hidden the container using width and height = 1px, and then when I want to see the video I change dinamically the size.
Here is an example:
var player = new YT.Player( containerId, {
height: 'auto',
width: 'auto',
suggestedQuality:"hd720",
"videoId":"ejWGThDRllE",
playerVars: { 'autoplay': 0, 'controls': 1,'autohide':1,rel:0,hd:1 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
container = document.getElementById(containerId);
container.style.width = "1px";
container.style.height = "1px";
onPlayerReady(event){
player.playVideo();
var playerr = document.getElementById(self.containerId);
playerr.style.display = "block";
playerr.style.width = "100%";
playerr.style.height = "100%";
}
hope it helps.
Upvotes: 1
Reputation: 1313
Try wrapping your script with this, if not already done :
$( document ).ready(function() {
//Script
});
It saved me from some strange behaviours!
Upvotes: 0