Skip to content
Advertisement

onYouTubeIframeAPIReady function is not calling

I want to call onYouTubeIframeAPIReady function but this is not firing. I am getting only frameID in console but other functions are not getting called.

$(document).ready(function(){
    var player;
    var ytsrc = $('.video_holder_frame').find('iframe').attr('src');
    if (ytsrc) ytsrc = ytsrc.match(/youtube.com/embed/([^\?]*)/i);
    if (!ytsrc) return;
    var frameID = 'youtube_' + ytsrc[1];    
    console.log(frameID);
    $('.video_holder_frame').find('iframe').attr('id', frameID);

    function attachToYoutubeFrame() {
        console.log("attachToYoutubeFrame");
        function onytplayerStateChange(newState) {
            console.log("onytplayerStateChange");
            console.log(newState);
        };

        player = new YT.Player(frameID, {
            events: {
                "onStateChange": onytplayerStateChange
            }
        });
    };

    function onYouTubeIframeAPIReady() {
        attachToYoutubeFrame();
    };
});

Advertisement

Answer

Your onYouTubeIframeAPIReady() function must be defined globaly. Simply replace the line

function onYouTubeIframeAPIReady() {

with

window.onYouTubeIframeAPIReady = function() {

It is also important to load the youtube iframe api library file:

<script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>

Also your iframe src url must have appended the enablejsapi=1 parameter:

http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1
Advertisement