davids
davids

Reputation: 5597

Prevent subsequent autoplay in youtube javascript API

I load and play a youtube video in a fancybox. It all works perfectly, except when I close the fancybox it starts the video again.

var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
        height: '480',
        width: '853',
        videoId: 'I76i-TCaUCY',
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

// autoplay video
function onPlayerReady(event) {
    event.target.playVideo();

}

// when video ends
function onPlayerStateChange(event) {
    if (event.data === 0) {
        $.fancybox.close();
    }
}

The user should be able to play it again if needed, so I can't delete it.

How do I play it for the first time only?

Upvotes: 0

Views: 758

Answers (1)

davids
davids

Reputation: 5597

I don't know if there is an easier way, but this is how I have fixed it for my needs:

I added var played = false and:

// autoplay video
function onPlayerReady(event) {
    //This ensures that it is autoplayed only once.
    if (!played) {
        event.target.playVideo();
        played = true;
    }
}

It now works as I was expecting.

Upvotes: 1

Related Questions