I want to add the youtube iframe api code inside my $(document).ready() function but when I do this the player doesnt seem to load, when i move the code outside the document.ready the player loads in fine. Can anyone offer me any suggestions on how i can make this video appear when inside the function?
JS
$(document).ready(function() {
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady() {
console.log('ready');
}
function onPlayerStateChange() {
console.log('player changed');
}
});
If you change function onYouTubePlayerAPIReady() {...}
to window.onYouTubePlayerAPIReady = function() {...}
then it's possible to define your YouTube iframe API callback within the $(document).ready()
function, and potentially pull in other variables from the $(document).ready()
scope into your callback scope.
I'm not sure there's much of an advantage to doing that, though, but it's an option if you really want to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With