Interactive feature allowing all embedded YouTube videos on a webpage to play synchronously, with sound disabled, and on a continuous loop

I am in the process of developing a button that, when clicked by a user, will trigger all embedded YouTube videos on a specific webpage to start playing simultaneously, with sound muted, and set to loop.

The target page for this button implementation can be accessed here - www.missingnewyork.com/last-seen

For embedding each video, I am utilizing the following code, which now incorporates ?enablejsapi=1 after each URL -

    <div id="horizontalcontainer">
        <div id="scrolling-wrapper-video">
            <div class="videocard1">
                <div style="padding:56.25% 0 0 0;position:relative;"><iframe src="https://www.youtube.com/embed/1i3x82LoQ1M?enablejsapi=1" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
            </div>              
            (additional video card code snippets...)
        </div>
    </div>

I attempted to use the provided function from a previous post to achieve the desired functionality -

function playAllVideos() {
    var videos = document.querySelectorAll('iframe[src^="https://www.youtube.com/embed/"]');
    videos.forEach(function(video) {
        video.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
        video.contentWindow.postMessage('{"event":"command","func":"mute","args":""}', '*');
        video.contentWindow.postMessage('{"event":"command","func":"setLoop","args":"1"}', '*');
    });
}   

Here is the button I have set up for this purpose -

<button id="play-all" style="position: fixed; top: 20px; left: 20px;">PLAY ALL</button> 

And the script to link the button with the function -

var playAllButton = document.getElementById('play-all');

playAllButton.addEventListener('click', playAllVideos);

However, upon clicking the button, no action is observed. I suspect there might be an issue in the last portion of the code... Can anyone spot where I might have made a mistake?

Just to clarify, my intention is for the videos to auto-play, loop, and stay muted only when the user clicks on the PLAY ALL button. Otherwise, the page should function as it currently does.

Thank you for any assistance provided!

Answer №1

Here are a couple of solutions to solve the issue;

First Option, In order to make your function work properly, you need to add ?enablejsapi=1 to the url and include allow="autoplay" in the iframe tag (which you are already allowing "autoplay" in the iframe).

<iframe src="https://www.youtube.com/embed/x-UprcCZIX0?enablejsapi=1" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

function playAllVideos() {
    var videos = document.querySelectorAll('iframe[src^="https://www.youtube.com/embed/"]');
    videos.forEach(function(video) {
        video.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
        video.contentWindow.postMessage('{"event":"command","func":"mute","args":""}', '*');
        video.contentWindow.postMessage('{"event":"command","func":"setLoop","args":"1"}', '*');
    });
}

Source

Second suggestion, (not the most ideal) involves changing the src of the iframes to include

?autoplay=1&mute=1&loop=1
options. This method may not provide the smoothest experience as it requires reloading all the videos, but it does get the job done. I tested this on the website you mentioned.

If you wish to stop all videos, simply remove these options from the source.

function playAllVideos() {
    var videos = document.querySelectorAll('iframe[src^="https://www.youtube.com/embed/"]');

    videos.forEach(function(video) {
        video.src = video.src + "?autoplay=1&mute=1&loop=1";
    });
}

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

Restrict the selection of dates in the jQuery UI datepicker by disabling public holidays, weekends, the next day after 10am, and only allowing Tuesday, Wednesday, and Thursday as

I found a code snippet on disabling weekends, public holidays, and the next day after 10 am using JQuery UI Datepicker. However, I'm facing an issue where I want to restrict selections to only Tuesday, Wednesday, and Thursday. // JavaScript logic for ...

Transfer or duplicate an SVG image from the bottom div to the top div

Is there a way to move a div from the chart_div to the movehere div? I've tried duplicating it below the current svg, but I'm having trouble targeting just the header row ('g' element) specifically. Here is the HTML: <script type= ...

Flask Pagination : UnboundLocalError occurs when trying to reference a local variable 'res' before it has been assigned

I'm currently troubleshooting an issue with flask pagination. Whenever I attempt to implement it, I encounter the UnboundLocalError. Even after removing all variables, the pagination feature still fails to function as intended. @app.route('/&apos ...

I am confused about the process of mounting components

Utilizing pattern container/representational components, I have a CardContainer component that retrieves data from a server and passes it to a Card component. Container Component: class CardContainer extends Component { state = { 'ca ...

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

Captivating captions for captivating visuals. Pictures don't conform to a linear arrangement

As someone who is new to website creation, I am currently working on adding a CSS effect where a popup-text appears when an image is hovered over. I want to create a row of images for the popups by using an unordered list. However, I'm facing a proble ...

A problem arises when making an ajax call

I'm struggling with an Ajax call made using the jQuery .blur() method. Every time I try to execute it, an error message pops up. Any idea why this is happening? Here's my jQuery/Ajax Code: <script> $("#given_name").blur(function(){ va ...

The Ajax request was a success, but I am unable to retrieve radio button values from the $_POST variable

My website operates fully asynchronously, generating and destroying HTML elements on button clicks that prevent navigation. In this section, I am creating a form with an array of radio boxes for rating from 1 to 10. This form is submitted using jQuery.aja ...

What is the process of overriding methods in a function-based component in React?

Overriding in a parent component works when it is a class-based component // Parent Button Class class Button extends React.Component { createLabel = () => { return <span>{this.props.label}</span>; }; render() { return <butt ...

Effortless sliding panel that appears on hover and vanishes when mouse is moved away

I am in the process of creating a menu for my website that utilizes linkbuttons which trigger additional linkbuttons to slide down upon hover. The desired effect is a smooth sliding panel that appears when hovering over the linkbutton, and disappears when ...

How can I trim a value using one-way data binding in Angular?

Is there a way to trim values in Angular using one-way data binding? Can this be done directly in the component.html file rather than in typescript? I tried the following but it didn't work: <P>{{country.trim()}}</P> Thanks ...

The process of isolating each variable within a JSON data structure

After making an ajax call, my JSON data is currently displayed in this format: {"main_object":{"id":"new","formData":"language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablesco ...

Limit the Jquery selection specifically to elements on the modal page

Recently I encountered an issue with a webpage that opens a modal form. The problem arises when the validation function, written in JQuery, checks all fields on both the modal and the page beneath it. //validate function function validateFields() { v ...

Convert JSON data into a Google chart with a dynamic number of columns and arrays

Modify my variable chart which currently holds this JSON: [{ "month": "January", "values": [0, 0, 0, 0, 0, 0, 0, 0, 0] }, { "month": "February", "values": [0, 0, 0, 0, 0, 0, 0, 0, 0] }, { "month": "March", "values": [35, 3, 8, 18, ...

Update overall font size to be 62% for a consistent look across the website

Recently, I developed a browser extension that adds an overlay button to the LinkedIn website. Everything was running smoothly until I discovered that LinkedIn uses a global font-size: 62,5% that completely messes up my design.. https://i.stack.imgur.com ...

How about displaying the Ajax response as an image?

I'm working on a script that pulls an image link, which seems to be functioning correctly. However, I am struggling with how to display the link as an image. Can someone please assist me with this? <script src="//ajax.googleapis.com/ajax/li ...

Webpack-hot-middleware increases the number of event listeners exponentially

When configuring my new development environment (node server + client with vanilla js), I encountered an issue with webpack-hot-middleware for live reloading front-end changes. The problem arose when using code like: $button.addEventListener('click&a ...

Updating the content of a div when the mouse hovers over it

Looking for some help here - I have a few divs with paragraphs of text inside. My goal is to change the text in each div when it's being hovered over. I know this can be done using JavaScript (jquery perhaps?), but my coding skills are pretty basic. A ...

The Angular ng-repeat directive is populating a list with items, but the parameters enclosed in double curly braces

After calling an API, the response contains data in the following format: [{name: "ABC", age: 20}, {name: "DEF", age: 25}] Even though the $scope.names variable is assigned with the array from the API, when viewed in the browser, it displays 2 rows but th ...

include a new value to the current state array within a react component

I am working with an array in React State and I need to add a new property called Value. However, every time I try to add it, it creates a new item in the array. What I actually want is for the new property to be added as follows: value: '' Belo ...