Search code examples
javascriptfunctionyoutube-apilimitmute

Limit function to 1 execution youtube player api


So basically I have embedded a video which should not autoplay and when played be muted, the code works fine but I only want it to run the onStateChange function once otherwise whenever you play/pause the video it mutes the video. Does anyone know how to limit that function to a single execution? Help is much appreciated :)

function onYouTubeIframeAPIReady() {
    player = new YT.Player('video-placeholder', {
        videoId: 'sAhYEfQ1168',
        playerVars: {
            'autoplay': 0,
            'controls': 0,
            'autohide': 1,
            'wmode': 'opaque',
            'showinfo': 0,
            'loop': 1,
            'fs':0,
            'rel':0
        },
        events: {
           'onReady': onPlayerReady
        }
    });

}

function onPlayerReady(event) {
    player.mute();
}

Solution

  • You could set the onReady property of player.events object to null within and at last line of onPlayerReady function

    function onPlayerReady(event) {
        player.mute();
        player.events.onReady = null;
    }