How to pause youtube videos when a new video is played?

Asked

Viewed 404 times

2

I have a website where I made a Youtube video Carousel using iframe, but when I browse the Carousel the video keeps playing.

How can I pause automatically when a new video is played?

1 answer

1

To automatically pause a video you have to use the API of Youtube 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 fully customized player in your own way.

Here is an example of what the code would be like 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.