"Enhance Your Website with Multiple Video Streams using YouTube API Events

Hello everyone!

I am looking to include multiple videos on my website and have them start playing automatically when a user scrolls and the videos are in view. I want the speakers to be muted by default using the mute() function.

Previously, I had success with one video on a single page, but now that I'm trying to add multiple videos, I'm encountering some issues. Can you help me figure out what I'm missing in my code?

Below is the HTML part:

<div class="video-container">
<div data-id="olBOo_S5AHY"></div>
</div>

<div class="video-container">
<div data-id="3IXKIVZ9T-U"></div>
</div>

<div class="video-container">
<div data-id="LAQDcnwwspQ"></div>
</div>

And this is the JavaScript part:

function onYouTubePlayerAPIReady() {

var players = document.querySelectorAll('.video-container div')

for (var i = 0; i < players.length; i++) {
    new YT.Player(players[i], {
        width: 600,
        height: 400,
        videoId: players[i].dataset.id, 
         events: {
         onReady: initialize
        }
    });
}
}

function initialize(){

players[i].mute(); // Need help fixing this issue

var waypoints = jQuery('.video-container').waypoint(function() {


    if( players[i]) { // Need help fixing this issue
       var fn = function(){ 
        players[i].playVideo();  // Need help fixing this issue
       }
       setTimeout(fn, 1000);
    }

}, {
  offset: '50%'
})
}

The videos are displaying on my site, but I'm struggling to add these events to each individual video. What am I doing wrong? Any assistance would be greatly appreciated!

Thank you so much!

Melanie

Answer №1

Hey Milenoi,

Your collection of divs stored in the players variable is not directly linked to the YouTube elements you want to manipulate. You will need to assign the YouTube player objects to a specific location in order to control them individually. Alternatively, there might be another method to locate and address these elements.

I have provided a demonstration on this functioning setup in my sample code here: http://jsbin.com/hozaluzaho. In this example, as you scroll down, additional players are activated. Take note of how I created and managed the necessary objects for this functionality.

// Obtain .player nodes
var playerDivs = document.querySelectorAll(".player");

// Convert nodelist to array for forEach();
var playerDivsArr = [].slice.call(playerDivs);

var players = new Array(playerDivsArr.length);
var waypoints = new Array(playerDivsArr.length);

// Callback function when YouTube resources are ready
function onYouTubeIframeAPIReady() {

  // Create YouTube players
  playerDivsArr.forEach(function(e, i) { // Loop through each item ...
    players[i] = new YT.Player(e.id, {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: { /* No events specified */ }
    })
  })

  // Create waypoints
  $(".player").each(function(i, e) {
    waypoints[i] = new Waypoint({
      element: e,
      handler: function() {
        players[i].playVideo();
      }
    })
  });

}

Additional Note:

Hello again,

No need to worry. In your initialize function, ensure that you iterate over the array containing multiple YouTube player objects; you must engage with each individual object instead of just one generic player variable within the initialization function (which may not have been defined if you followed my previous code?). Refer to the section labeled create yt players above. Each slot in the players[] array is filled with a distinct player-object. To mute each player, you will need to interact with every object in the array using a loop like forEach.

function initialize() {
  players.forEach(function(yt, i) {
    yt.mute();
  });
}

Here is an alternative demo: http://jsbin.com/ficoyo/edit?html,output

Cheers!

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

Leverage the power of Reactjs to add hover effects to a mapped

I am facing a challenge in styling the ListItem on hover. The issue arises when the list is dynamically generated, causing all list items to change style simultaneously when hovered over. How can I target only one element for styling? Below is the code sni ...

A step-by-step guide on accessing the data from an uploaded JSON file in a React application

One exciting feature is the drag and drop component that allows users to add multiple files. However, there seems to be an issue with displaying the content of a JSON file once it's added. Below is the code snippet in question: if (files?.length) ...

Encountering an issue with Meteor and node-celery: "Unable to access property 'slice' of null"

Check out the Github repository for reproducing this issue Run localhost:3000 to replicate the problem. In my setup with Meteor 1.4.4.1, I am utilizing the node-celery npm packages on the server side. Upon Meteor initialization, the client automatically i ...

Creating Beautiful Tabs with React Material-UI's Styling Features

I've been delving into React for a few hours now, but I'm struggling to achieve the desired outcome. My goal is to make the underline color of the Tabs white: https://i.stack.imgur.com/7m5nq.jpg And also eliminate the onClick ripple effect: ht ...

Consider yourself a module for npm, just like a node

I'm currently working on a Javascript project that has been released as a node module. In some parts of the source code, I have used relative paths to import other files within the project: // <this_module_path>/action/foo.js import execution f ...

When implementing dynamic routing in Next.js, an error occurs with TypeError: the 'id' parameter must be a string type. It is currently

I’m encountering a problem while creating dynamic pages in Next.js. I'm fetching data from Sanity and I believe my code is correct, but every time I attempt to load the page, I receive a type error - “the ‘id’ argument must be of type string. ...

What is the best way to call an API within a loop using Node.js?

How can I efficiently make API calls based on page numbers in a loop? I am using the request() function for API calling, but when debugging my code, the response block is not reached and I do not get a response. Can someone please provide guidance on how ...

Managing the clearing of a view component in React or Vue.js

In my project, I have a container component that handles all the business logic, ajax requests, and data management. This container component has child components to which it passes data and methods as props. For example, there is a "CommentForm" compone ...

Python script for extracting data from live YouTube chats

I am attempting to extract chat messages from YouTube live chat. Initially, I tried a method outlined in "https://www.youtube.com/watch?v=W2DS6wT6_48" Unfortunately, the code did not function as expected. An error message was generated: all_comments = d ...

Verifying the content of the JSON data

If I receive JSON data that looks like this: {"d":1} Is it possible to determine whether the value after "d": is a 1 or a 0? I attempted the following method, but it always goes to the else block, even though I know the JSON data contains a 1. success: ...

Utilizing Axios for Vue Multiselect on select/enter Event

I have successfully implemented a Vue Multiselect feature that retrieves options from my database using an axios call. This functionality works great as it allows users to select existing options or add new ones to create tags. While this setup is working ...

The functioning of JavaScript's ajax capabilities

Need some help with a coding issue I'm facing. Can anyone provide suggestions for improving my code? I've come across a situation where the table is not updating when using a certain piece of code. However, upon further inspection, I found that ...

Incorporate Angular frontend into current website or project

I've successfully built a website using bootstrap, but now I'm looking to integrate Angular in order to transform it into a single page application. The goal is that when a user clicks on a link, only the necessary content will be loaded from the ...

Filter the ng-repeat list dynamically by triggering ng-click event

I am currently developing an application on that requires users to be able to filter a list of credit cards by clicking on filters located on the interface, such as filtering for only Amex cards or cards with no fees. Although I have successfully bound t ...

Initiate an Ajax request from a hyperlink

Is it possible to trigger an Ajax request from a hyperlink? I am interested in updating the inner html of a div element upon clicking on a hyperlink through JavaScript. ...

What is the method for determining the level based on the provided experience points?

I've created a formula that can calculate experience based on specific levels and another formula that calculates the level based on given experience. However, there seems to be an issue with the second function as it is not returning the expected val ...

Issue with Swiper js "autoheight" not resizing correctly for the height of the first slide upon page initialization

Hey everyone, I'm encountering a problem with my reactapp and I'm not sure how to resolve it. I've spent a considerable amount of time searching on stackoverflow but haven't come across any helpful solutions. The issue is related to a ...

Are there any instances of a race condition present in the following?

In the express server code snippet provided, there is a common object that is being manipulated in three different RESTful endpoints. Given that all HTTP requests in Node.js are asynchronous, it's possible to have simultaneous PUT and GET requests occ ...

Adding x days to a Unix timestamp can be achieved by converting the Unix timestamp

Currently, I have the following code snippet: let currentTS = Math.floor(+new Date() / 1000) This code successfully retrieves the current date in a unix timestamp. However, my goal now is to append an additional 14 days to this unix timestamp. Could some ...

Ensure your HTML5 videos open in fullscreen mode automatically

I managed to trigger a video to play in fullscreen mode when certain events occur, such as a click or keypress, by using the HTML 5 video tag and jQuery. However, I am now looking for a way to have the video automatically open in fullscreen mode when the p ...