"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

Error: Attempting to use hooks outside the scope of a function component in react-native. Hooks can only be called within the body of a

Oops! An error occurred: Invalid hook call. Hooks can only be called inside the body of a function component. There are several reasons why this might have happened: You could have incompatible versions of React and the renderer (e.g., React DOM) Your cod ...

waiting for deferred to complete in esri javascript api before continuing with code execution - labelPoints

I'm encountering an issue with obtaining my labelPoints before completing the rest of my code. It seems to be related to a deferred/callback problem that I can't quite grasp, and I couldn't find many examples using the esri javascript api. ...

Interactive element for initiating a HTTP request to NodeJS/Express server to trigger a specific function

I currently have a frontend button implemented using nodejs and express for my server-side backend. The button is supposed to trigger a function that controls the Philips Hue API on the backend via an HTTP request. I have experimented with various approac ...

Can you provide the proper syntax for the Jquery done() function?

I'm currently dealing with the code below: However, I encountered an error on line 6: Uncaught SyntaxError: Unexpected token { Even after reviewing the documentation for the done() function, I'm unable to identify my mistake here. ...

In my experience, I have encountered issues with certain routes not functioning properly within Express

I am currently working on developing a tic-tac-toe game and looking to store user data in a database. However, I am facing an issue with the router I intended to use for this purpose as it is returning an 'Internal server error message (500)'. B ...

What is preventing me from loading a module using a variable containing a string?

This code snippet demonstrates how the module can be successfully loaded using import('test'), but not with the second example. These lines of code are executed within an Angular 9 application utilizing the default Webpack configuration. var tes ...

Fetch JSON information from various servers/domains through ajax requests

I am attempting to retrieve JSON data from a different server/domain. My expectation is that the code below should trigger a success alert, but instead, I am getting an error alert $.ajax({ url: "http://xxxx.com/zzzz", ...

Attaching this to the event listener in React JS

After delving into a beginner's guide on React JS, I encountered a slight hiccup. The issue revolves around a simple problem within the button element; specifically, an event handler that requires passing an argument. This handler serves the purpose o ...

List of coordinates extracted from PolylineMeasure plugin in the React Leaflet library

I have 3 different scripts: 1. PolylineMeasure.jsx import { MapControl, withLeaflet } from "react-leaflet"; import * as L from "leaflet"; class PolylineMeasure extends MapControl { createLeafletElement() { return L.control.poly ...

What is the process for creating a symbolic link from a project's node_modules directory?

Recently, I've been learning how to build a Password Manager using React, Node.js, and MYSQL by following a tutorial. However, I encountered an issue where the file /EncryptionHandler was located outside of the src/ directory of my project. Even thoug ...

Is it possible to retrieve server data in a JavaScript file?

EDIT: I accidentally omitted a piece of relevant code I am looking to access the "jsonData" value from my server in my JavaScript file. Can someone guide me on how to retrieve these values? Here is the server-side code: var express = require('expre ...

Stopping the papaparse streaming process once a certain number of results have been achieved

Currently, I am utilizing the PapaParse library to parse a large CSV file in chunk mode. During my data validation process, I encountered an issue where I was unable to stop streaming the data once validation failed. I attempted to halt the streaming by ...

A guide on extracting the text content from an anchor tag by using xPath() with a combination of selenium and Mocha

I have successfully chosen an <a> tag. My goal is to display the text of the anchor tag, but I am facing difficulties. The technologies being used are selenium, mocha, javascript, and phantomJS This is the detailed script: var assert = require(&ap ...

Unable to create the complete PDF file using html-pdf in a NodeJS environment

When trying to create a PDF from an HTML template, I am encountering some difficulties. While it works with static entries, I want to generate the PDF for multiple items that can vary each time. I feel like I might be overlooking something, so any suggesti ...

Obtaining the source code from a different domain website with the help of jQuery

Is there a way to extract part of the source code from a YouTube page without using server-side programming? I've tried cross-domain AJAX techniques like Yahoo YQL and JsonP. While Yahoo YQL allows me to grab part of the source code, I'm facing ...

When using the "Content-Disposition" header with the value "inline;filename=" + fileName, it does not necessarily guarantee that PDF files will be displayed directly

When a link is clicked, I want the PDF file to first show in a new tab as a preview before allowing users to download it. I researched and found advice suggesting that including these two headers would achieve this: Response.AddHeader("Content-Dispositio ...

Possible solutions for AngularJS using ng- tags

I absolutely love incorporating AngularJs into my Multiple Pages Laravel Application. However, using the Laravel Blade Template Engine has made me reconsider adding Angular Tags to clutter my blade templates. For instance <div ng-controller="TodoCont ...

Extract the content of an element and incorporate it into a script (AddThis)

HTML: <div id="file-section"> <div class="middle"> <p class="description"> Lorem ipsum... </p> </div> </div> jQuery: var share_on_addthis = { description: $('#file-section ...

Implement a click event using jQuery specifically for Internet Explorer version 7

How can I add an onclick attribute using jQuery that is compatible with IE7? So far, the following code works in browsers other than IE8 and Mozilla: idLink = Removelst(); var newClick = new Function(idLink); $(test1).attr('onclick', null).clic ...

Master the art of returning two functions within a single function in Javascript with NodeJS and ExpressJS

Currently, I am facing an issue where I need to combine two objects and return them in one function. The challenge lies in the fact that both objects have almost identical properties, but different values. To tackle this problem, I created two separate fu ...