Prevent any YouTube iframe from playing when a different one is activated

I have a unique challenge where I need to embed 10 YouTube iframes in my webpage, each with its own custom play/pause buttons. While I started with this solution from http://jsfiddle.net/buuuue/dzroqgj0/, I am struggling to modify the code to ensure that when one video starts playing, any other currently playing videos are paused...

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

For instance, if player 1 is active and player 3 is initiated, I want to automatically pause player 1. Although I came across this helpful solution at , it seems like I might need to generate the players using JavaScript so I can integrate the customized play/pause controls.

Any assistance would be greatly appreciated!

Answer №1

Once you have created the players, add them to an array.


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

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

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

You can access each player object's id through its a.id property (a is an object itself, id is a string property).

When a user plays a specific player, you just need to pause all others except the one being played (you can get its id in the stopVideo). This task becomes easy since you have the id.


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/

If you are not generating players through scripts but simply embedding iframes, then refer to this answer provided by vbence. The following is a demo with enhancements suggested by Jennie

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

All credits go to the original authors of these solutions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for jQuery to detect if an email was sent from the client's email account?

I am working towards a feature on my website where users fill out specific fields and then click "send email" to activate their email platform via "mailTo", with the email pre-populated for easy sending. The challenge lies in confirming if the user actuall ...

Deciphering the Cause of mapStateToPropsCall in Redux and React

When handling an unsuccessful http call resulting in an error message being displayed, I encounter subsequent state changes triggering multiple render calls. Is there a technique to identify the cause of these state changes and mapStateToProps calls? Alter ...

When adding an object to an array in AngularJS, it seems to trigger updates for

Currently, I am fetching data from a WebAPI and then storing it in an array called products, which is scoped. $scope.products In addition to the products array, I also have another scoped array named selectedFish. $scope.selectedFish = []; My objective ...

Executing multiple asynchronous function calls within a for loop using JavaScript

Developing a mini Instagram-like bot for checking. The bot operates by using an object that contains a list of users from a chat along with their Instagram usernames. The issue I am encountering is related to asynchronous calls within loops. The loop con ...

Removing message board posts

In my database table, I have fields called wall_posts, group_id, id, and user_id. Wall_posts store user entries, group_id is a unique identifier imported from another table, id is a simple counter, and user_id holds the user id retrieved from the session. ...

Transform the decimal numbers within an array into percentages before feeding all the values into a graph

I'm currently working on converting an array of decimals to percentages to effectively display the data as percentages in my chart created with chart.js. Below is the array that I am dealing with. https://i.sstatic.net/HVXLi.png During my data mappi ...

Having trouble retrieving a specific key from the state object in Redux using TypeScript

I have incorporated TypeScript into my Ionic project, using React hooks. I recently added an errorReducer to handle any errors that may arise from the server. Below is a snippet of my code: Action import { ERROR_OCCURRED } from "./types"; ...

What's the best way to incorporate local storage into my Calculator application?

I'm currently working on a calculator project and I have all the necessary resources at hand. The only thing left to do is to incorporate LocalStorage beneath the Result section. This way, the Calculator will keep track of each result until the sessio ...

What is the correct way to update the state in an array of objects using useState?

I'm struggling to figure out how to use the React useState hook properly. In my todolist, I have checkboxes and I want to update the 'done' property to 'true' for the item that has the same id as the checkbox being clicked. Even th ...

Storing JSON data in an array using JavaScript is a powerful method to

Here is an example of JSON data: [{ "address": "A-D-1", "batch": [{ "batch_number": "B-123", "cost": [{ "cost": "C1" }] }] }, { "address": "A-85-1", "batch": [{ "batch_number": "B-6562", ...

Unable to view Vue.js bulma modal pop-up

When a link is clicked, I want to trigger the opening of a modal: <a @click="showEditModalFunc()" href="#">Edit Post</a> The function itself: showEditModalFunc() { console.log('showEditModal value is' , this.showEditModal); ...

How can Angular 7 be used to accept a ZIP response from an API?

My attempt to download a zip file to my local system using Angular's API response with the desired type as zip has been unsuccessful. Despite specifying the correct content-type and Accept headers, I keep encountering errors. a.service.ts download( ...

Generating a linked pledge with AngularJS

I need to create a linked commitment for my service provider: this.$get = function($q, $window, $rootScope) { var $facebook=$q.defer(); $rootScope.$on("fb.load", function(e, FB) { $facebook.resolve(FB); }); $facebook.api = functi ...

Implementing NodeJS to showcase an array of items - the step-by-step guide

I'm currently setting up a webpage to display a list of books using NodeJS, but despite my efforts, the page remains blank when I launch it. My goal is to showcase the array of books on the page, and so far, here's the code that I have written. A ...

Discover in Mongo DB with Mongoose, except for the find() method, which excludes documents containing a specific property

I'm searching for a condition in Mongoose that will help me locate all users except those with the role 'Admin':2000. Keep in mind that admin users also have other roles, such as "User" and "Editor", as shown below: { "name": &q ...

Applying Styles to Cells Using the Google Sheets API (v4)

Having encountered an issue while using the Google Sheets API (v4) for programmatically creating or updating spreadsheets, I have come across the following problem: According to the documentation (https://developers.google.com/sheets/api/reference/rest/v4 ...

Unable to .map two separate arrays within the same table row, <tr>

I am currently facing an issue with mapping entries to a table. The entry I am working with has a column that can contain multiple values, requiring the creation of sub-rows within the same row. I have provided an example image below to illustrate the desi ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...

Revamp your JavaScript code to trigger when the clock strikes bold!

Having trouble setting up JavaScript to automatically bold the next clock time. Any tips on rewriting the JavaScript? For instance, if it is currently 6:49, I want the next clock time of 7:32 to be automatically bolded. And when the time reaches 7:32, I wa ...

Creating a BPMN web-based designer using JavaScript

In search of a web-based UI tool to design and save bpmn workflows as XML for integration with an Angular front end. As a starting point, I need to draw bpmn shapes. Does anyone have suggestions on the best method to accomplish this using JavaScript? I&apo ...