I am playing an embeded youtube video with the play() function. This is all using the youtube api. Below is the code I have. It works perfectly in chrome and IE but in firefox it doesnt play.
alert(typeof ytplayer);
This bit of code is showing what type “thing” ytplayer is. In chrome and IE it will come up with object (the video is embed with the object method). In firefox it says undefined so something is going wrong there.
I have a test website with it here: http://lostinawesome.blogspot.com.au/2012/04/test-post.html
click the play button or the image to play the youtube audio. In firefox it probably wont work for you.
Any ideas to get this to play in FF?
my code:
javascript:
function onYouTubePlayerReady(playerId) {
var player = document.getElementById("ytplayer");
player.addEventListener("onStateChange", "onytplayerStateChange");
}
function onytplayerStateChange(newState) {
alert("New state " + newState);
}
function play() {
alert(typeof ytplayer);
if (ytplayer) {
ytplayer.playVideo();
}
}
html:
<object data="http://www.youtube.com/v/u8C-ZTQJIkU?enablejsapi=1&playerapiid=ytplayer&version=3" height="400" id="ytplayer" type="application/x-shockwave-flash" width="550"><param name="allowScriptAccess" value="always">
<param name="movie" value="http://www.youtube.com/v/u8C-ZTQJIkU?enablejsapi=1&playerapiid=ytplayer&version=3" >
</param>
<param name="allowScriptAccess" value="always">
</param>
</object>
<a href="javascript:void(0);" onclick="play();">Play</a>
Working code:
I just had to change to have var ytplayer = document.getElementById("ytplayer");
because ytplayer wasnt declared as a variable anywhere but for some reason it worked in chrome and IE anyway.
function play() {
var ytplayer = document.getElementById("ytplayer");
alert(typeof ytplayer);
if (ytplayer) {
ytplayer.playVideo();
}
}
You need to explicitly select the element rather than just using its ID since it won’t work in all browsers, as you’re seeing.
Change to