I have the following code, necessary to track an embedded Youtube video in my page using their Javascript API:
function onYouTubePlayerReady(playerId) {
var youtubeplayer = document.getElementById('youtubeplayer');
youtubeplayer.addEventListener("onStateChange", "onytplayerStateChange");
youtubeplayer.setPlaybackQuality('large');
}
function onytplayerStateChange(newState) {
//Make it autoplay on page load
if (newState == -1) {
youtubeplayer.playVideo();
}
var tiempo = youtubeplayer.getCurrentTime();
//Rounds to 2 decimals
var tiempo = Math.round(tiempo*100)/100;
alert(tiempo);
}
(The details related to the Youtube API aren't important, but if you are curious, they are at my previous question Youtube Javascript API: not working in IE).
Now, my problem is that the onYoutubePlayerReady() function declares "youtubeplayer", which is a reference to a DOM object, and I need to access that variable from the other function onytplayerstateChange() too... but "youtubeplayer" is being declared as a local variable. This works in IE 8, Safari..., but doesn't work in Firefox 12. Of course, I could get a reference to "youtubeplayer" in the following way instead, without the "var":
youtubeplayer = document.getElementById('youtubeplayer');
And in fact, that is how it looks in Youtube's sample code, but if I write it this way, the code doesn't work in IE 8 (while it does work in Firefox 12; see my previous question for more details).
...All of which brings me to: is there a way to declare a global variable from inside a function (like "youtubeplayer" above), so that it can be accessed by other functions too? Something that works in all browsers?