Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YouTube API - onPlayerStateChange

I'm using the YouTube API in conjunction with Cyclone Slider. The goal is to pause the slideshow once the YouTube starts playing. I'm using the following code which works nicely:

<script>
var tag = document.createElement('script');
 tag.src = "//www.youtube.com/iframe_api";
 var firstScriptTag = document.getElementsByTagName('script')[0];
 firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>

<script>
var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('video', {
      events: {
        'onStateChange': onPlayerStateChange
      }
    });
}

function onPlayerStateChange(event) {
    if(event.data === 1) {
        $(".cycle-slideshow").cycle('pause');
    }

    if(event.data === 2) {
        $(".cycle-slideshow").cycle('resume');
    }
}
</script>

However, it only seems to work if I do a refresh of the page. If I navigate between pages and return to the homepage, it will no longer work.

Any suggestions for why this is the case? I've tried a few suggestions I found on Google but couldn't get any to work. I'm a little lost on this one.

Any help would be greatly appreciated.

like image 741
Pete Avatar asked Mar 23 '26 17:03

Pete


1 Answers

Try the following code, it works for me -

function loadYouTube(targetId){
    ytplayer = new YT.Player(targetId, {
        events: {
            'onStateChange': function(event){
                /** YouTube API
                        -1 (unstarted)
                        0 (ended)
                        1 (playing)
                        2 (paused)
                        3 (buffering)
                        5 (video cued)
                 **/
                if (event.data == 1) {
//do your work here
                }
                console.log(event.data)
            }
        }    
    });
}
like image 151
Zafar Ahmad Avatar answered Mar 26 '26 06:03

Zafar Ahmad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!