YouTube: Embed two videos on a single webpage

I have a JavaScript question regarding the YouTube API. I made some modifications to the YouTube iFrame API in order to display two videos simultaneously, with one playing automatically and the other not. However, I am facing an issue where only the second video is being shown.

Below is the code I have implemented:

    <script>
    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player1;

    function onYouTubeIframeAPIReady() {
        player1 = new YT.Player('player1', {
            height: '315',
            width: '420',
            videoId: 'bHQqvYy5KYo',
            events: {
                'onReady': onPlayerReady
            }
        });
    }

    var player2;

    function onYouTubeIframeAPIReady() {
        player2 = new YT.Player('player2', {
            height: '315',
            width: '420',
            videoId: 'M3uWx-fhjUc',
            events: {
                'onReady': stopVideo
            }
        });
    }

    function onPlayerReady(event) {
        event.target.playVideo();
    }

    function stopVideo() {
        player.stopVideo();
    }
</script>


<div id="player1"></div>
<br>
<div id="player2"></div>

After implementing the suggested fix, the updated code looks like this:

    <script>
    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player1;
    var player2;

    function onYouTubeIframeAPIReady() {
        player1 = new YT.Player('player1', {
            height: '315',
            width: '420',
            videoId: 'bHQqvYy5KYo',
            events: {
                'onReady': onPlayerReady
            }
        });

        player2 = new YT.Player('player2', {
            height: '315',
            width: '420',
            videoId: 'M3uWx-fhjUc',
            events: {
                'onReady': stopVideo
            }
        });
    }


    function onPlayerReady(event) {
        event.target.playVideo();
    }

    function stopVideo() {
        player.stopVideo();
    }
</script>


<div id="player1"></div>
<br>
<div id="player2"></div>

Answer №1

It appears there are two functions with the name onYouTubeIframeAPIReady. It would be beneficial to merge the code into a single function for better organization.

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

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

The Chrome browser on iOS does not fire the Image onLoad event

In my web application, I am utilizing Scala.js and d3.js (scala-js-d3) to generate an SVG. However, I have encountered a problem with the background image not triggering the load event when using Chrome on iOS (iPhone), even though it works fine on Windows ...

Node.js encountering issue with printing an array

Here is the code snippet from my routes file: router.get('/chkjson', function(req, res, next) { req.getConnection(function(err,connection){ var ItemArray = []; var myset = []; var query = connection.query('SELEC ...

What is the best way to retrieve the text when it is no longer within its original div?

Is it possible to use Javascript to detect when text is flowing out of its containing <div>? For instance, if a text consists of 3 sentences and the last sentence is only partially displayed, can JavaScript be used to capture the entire last sentence ...

Issue with vue-template-compiler in Vue.js 3 webpack configuration

I am currently working on integrating vuejs 3 into a project that already utilizes webpack. I have been looking into using vue-loader as part of this process. After consulting the official documentation, I came across the following information: Every new ...

Two Ajax Requests Simultaneously

I am currently faced with the challenge of handling two requests simultaneously. The first request involves executing a lengthy PHP script that takes 10 minutes to complete (I cannot modify it using JavaScript, so that's not an option). The second ...

Learn how to integrate Bootstrap with Vue.js TreeView in this tutorial

If you're looking to create a treeview using Vue.js, the code structure would resemble something like this: HTML: <!-- item template --> <script type="text/x-template" id="item-template"> <li> <div ...

Guide to retrieving information from Instagram api using Axios and Reactjs?

Having trouble rendering caption and image from Instagram posts after making an API call using Axios/Reactjs. Any assistance would be greatly appreciated. Thank you! import React,{Component} from 'react' import '../styles/home.css' ...

When attempting to make my styles responsive, I found that they broke due to duplicate classes on the landing page I was creating with next.js and styled components

Something strange is unfolding, and I find myself confused about the overall situation. Let me try to explain it the best I can. On my landing page, there are three different components: const Home = () => { return ( <> <Head> ...

Numpad functionality in JQuery malfunctioning post-ajax request

Using the jQuery numpad plugin has been flawless until after an AJAX call. I have tried various functions like on('click') and others, but unfortunately, none of them worked as expected. Apologies for my poor English! You can find the extension l ...

The XHR request fails to transmit a JSON object

Having a client-server express app, I am currently working on sending an XHR request from my frontend to the controller while passing JSON data. The code snippet from my frontend looks like this: function handle_login(){ var username_field = document. ...

Is it possible to generate a PNG blob using binary data stored in a typed array?

I have a piece of binary data that is formatted as a PNG image. I am looking to convert it into a blob, generate a URL for the blob, and then showcase it as an image in various places where an image URL can be used, such as CSS. My initial approach invol ...

Reimagining the _id Attribute in MongoDB Using JavaScript Objects

In my Express project, I am conducting the following test: it('testing club', async () => { let club = await clubDAO.create(baseClubParams); console.log(club) const resp = await http.put(`/api/user/follow/${club._id}`); isO ...

Render variable values with Mustache syntax

There are two separate html pages named home and about. Each page contains a js variable defined at the top of the page: var pageAlias = 'home'; // on the home page var pageAlias = 'about'; // on the about page The goal is to pass thi ...

Utilizing SVG elements for interactive tooltips

Can the < use > element show the rect tooltip on mouseover in modern browsers? Refer to 15.2.1 The hint element. <svg id="schematic" version="1.2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <symbol i ...

Utilizing XPath and nightwatch.js to interact with dynamic text elements with a simple click

When trying to click on an element with dynamic text in my app, I encounter a syntax error. Normally, to select an element by its text, I use the following format: .useXpath().click("//*[contains(text(), 'some text')]") But for elements with dy ...

What could be the reason for the failure of the .is(":hover") method?

Here is some code I'm using to fade out certain elements on a webpage if the mouse hasn't moved for a period of time: idleTime = 0; var idleInterval = setInterval(function() { idleTime++; if (idleTime > 1) { var isHovered = $ ...

Unable to update data from false to true in vue.js

What I'm trying to do is change the data from false to true in order to conditionally render a button when a payment has succeeded. When making an axios call, I receive 'succeeded' as the response in the JSON object and can log it to the con ...

Firefox experiencing issue with Ajax form submission

Hey there, I'm encountering an issue with the code below not functioning correctly and completely in Firefox. It should display a message (loading, check errors) from the server after clicking submit, but in Firefox it just performs a regular submit w ...

Calculating the total price of items in a shopping cart by multiplying them with the quantity in Vue.js

I am currently working on enhancing the cart system in Vue.js, with a focus on displaying the total sum of product prices calculated by multiplying the price with the quantity. In my previous experience working with PHP, I achieved this calculation using ...