Stop any built-in YouTube iframe when another is playing

I embed about 10 YouTube frames on my page, all with their own play / pause buttons. I used this solution to start http://jsfiddle.net/buuuue/dzroqgj0/ , but I'm not sure how to set up this piece of code to stop any other video that plays if another starts ...

function stopVideo(player_id) {
    if (player_id == "player1") {
        player2.stopVideo();
    } else if (player_id == "player2") {
        player1.stopVideo();
    }
}

For example, if player 1 is currently playing and player 3 is playing, I would like player 1 to stop playing. I also looked at this solution https://stackoverflow.com/a/3776161/2129 , but I think I need to create players through JS so that I can create custom play / pause buttons.

Thanks in advance for your help!

+4
source share
1 answer

After creating the players, click them on the array.

    var vids =[];
    player1 = new YT.Player('player1', {
     //stuff
    });
    vids.push(player1);

    player2 = new YT.Player('player2', {
     // stuff
    });
    vids.push(player2);

    ....
    ..
    playerN = new YT.Player('playerN', {
     // stuff
    });
    vids.push(playerN);

Each player object identifier can access a property a.id( aitself is an object, idis a property (string))

Now, when the user plays this player, you just need to pause all the others, except for what you play (whose id you get in stopVideo). Since you have id it's easy

 function stopVideo(player_id) {
  for(var i=0;i<vids.length;i++){
    if (player_id !=vids[i].a.id)    
      vids[i].stopVideo();
  }
 }

Example: - http://jsfiddle.net/4t9ah1La/

, iframe, vbence , , Jennie

: - http://jsfiddle.net/fyb7fyw1/

+3

Source: https://habr.com/ru/post/1665387/


All Articles