How to pause videos on YouTube when a new video is played?

2

I have a website where I made a YouTube video carousel using the iframe, but when I navigate through the carousel the video keeps playing.

How can I automatically pause when a new video plays?

    
asked by anonymous 16.09.2017 / 18:41

1 answer

1

To automatically pause a video you must use the YouTube API instead of the default iframe.

This API allows you to control simple things like events play state , pause , stop etc, or go to the extreme and create a completely customized player in your own way.

Here is an example of what code to pause the transmission of a player that is currently playing when a new video is clicked:

Example in jsFiddle: YouTube Pause / Play

<div id="player1"></div>
<div id="player2"></div>
<script>
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 onYouTubeIframeAPIReady() {
        player1 = new YT.Player('player1', {
            height: '200',
            width: '520',
            videoId: 'glaG64Ao7sM',
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
        player2 = new YT.Player('player2', {
            height: '200',
            width: '520',
            videoId: 'Z-48u_uWMHY',
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING) {
            pauseVideo(event.target.a.id);
        }
    }

    function pauseVideo(player_id) {
        if (player_id == "player1") {
            player2.pauseVideo();
        } else if (player_id == "player2") {
            player1.pauseVideo();
        }
    }
</script>
  

You can read more in this documentation in English: YouTube Player API - Getting Started

    
16.09.2017 / 20:21