After removing old elements and replacing them, videos in newly generated elements fail to play

In my game, I use div elements to represent characters, with each div containing a video child element that plays in a loop to animate the character. Whenever something happens on the screen, I delete all the character divs and recreate them for each character in the scene. However, I encountered a problem where switching frames (from one set of characters to another) caused the videos of the characters in the following frame not to play.

//Snippet from the applyFrame function responsible for displaying objects on the screen
//First, all character objects from the previous frame are removed
//mainFrame is the background holding other interactive objects

function applyFrame() {
for (let i = 0; i < mainFrame.children.length; i++) {
        mainFrame.children[i].children[0].pause();
        mainFrame.removeChild(mainFrame.children[i]);
    }

//New div objects are created for each character and a video element is appended to play animations
//currentFrame contains information about character positions, sizes, and media src

for (let i = 0; i < currentFrame.objects.length; i++) {
        let elem = document.createElement("div");
        mainFrame.appendChild(elem);
        mainFrame.children[i].style.opacity = "0";
        let video = document.createElement("video");
        elem.appendChild(video);
        video.classList.add("elemVideo");
        if (currentFrame.objects[i].video != "" || currentFrame.objects[i].video != undefined) {
            //Check for blob URL to assign it to the video element
            for (let j = 0; j < animationBlobsGLOB.length; j++) {
                if (currentFrame.objects[i].video == animationBlobsGLOB[j].name) {
                    //Assign the blob URL to the video element src
                    mainFrame.children[i].children[0].src = animationBlobsGLOB[j].blob;
                    //Play the video and set it to loop
                    video.play();  
                    video.addEventListener("ended", function() {
                        video.play();
                    });
                }
            }
        }
    }
}   

I suspect that deleting the divs containing the videos may be causing them to lose their events. This could explain the error message "Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()." Sometimes repeating the applyFrame function resolves the issue, but running it twice may not be ideal.

Answer №1

Resolved, in place of the initial solution:

mainFrame.children[i].children[0].src = animationBlobsGLOB[j].blob;
mainFrame.children[i].children[0].play();  
mainFrame.children[i].children[0].addEventListener("ended", function() {
      mainFrame.children[i].children[0].play();
});

I found that I needed to use this revised code instead:

mainFrame.children[i].children[0].src = animationBlobsGLOB[j].blob;
mainFrame.children[i].children[0].play();  
mainFrame.children[i].children[0].addEventListener("ended", function() {
      mainFrame.children[i].children[0].play();
});

Still not entirely clear on why the adjustment was necessary.

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

Tips for loading a webpage based on the selected value of a JQuery dropdown list

I'm currently working on an ASPX webpage where I am developing a feature to create reports using filter criteria. To populate my dropdown list, I am using a jqxwidget which retrieves values from a variable I have defined: var sourceRptType = [ ...

What is the best way to retrieve the current state from a different component?

My goal is to access a user set in another component. I passed the state from the highest component (which is the app) by utilizing this function for state change. handleRegisterSubmit(e, username, password) { e.preventDefault(); axios.post('/au ...

When using PHP's `json_encode()`, don't forget to append a "1" at the

While utilizing json_encode in my project, I have encountered an issue that is perplexing. On one particular page where I make an ajax call, the resulting json seems to mysteriously add a 1 to the end of the string. The output of my return string appears ...

Investigate duplicate elements within nested arrays using the 3D array concept

I am dealing with an array that contains 3 subarrays. Arr = [[arr1],[arr2],[arr3]] My task is to identify and store the duplicate values found in these subarrays ([arr1],[arr2],[arr3]) into a separate array. Arr2 = [ Duplicate values of arr 1,2,,3 ] What ...

Vue Router generates a URL containing %2F when dealing with slug routes

I am facing an issue in my Vue 3 application where I need to create a route for dynamic slugs. Currently, when using RouterLink, the generated URL contains %2F instead of actual slashes which is not the desired result. For example, the current URL looks l ...

JavaScript table search feature for novices - finding results

I am relatively new to this, but I am working on improving the workflow within my company. I found some code at this link in order to create an internal site for searching current part numbers. However, my employees are looking for parts based on descripti ...

JavaScript is failing to add items to an array

Attempting to add coordinates and user-specified data from a form to an array named "seatsArray". Here's the code snippet: <div> <img onLoad="shiftzoom.add(this,{showcoords:true,relativecoords:true,zoom:100});" id="image" src="plan1.bmp" wid ...

What is the best way to allow all authenticated routes to display the Devise ajax Login form?

I have successfully incorporated Devise to accept Ajax Login and have designed a form for logging in via ajax, displayed within a modal. However, I am only able to view the form and login when I set up event binders for specific buttons that activate the m ...

Converting milliseconds into days, hours, minutes, and seconds using Angular

Currently, I am attempting to convert milliseconds to the format dd:hh:mm:ss. For example, given 206000 milliseconds. The desired format for this value would be: 00:00:03:26. However, when utilizing the following code: showTimeWithHour(milliSeconds: numb ...

Searching for an object in Vue 3 Composition API and displaying its contents

Experiencing a challenge with my first Vue.js project, seeking assistance in resolving the issue. Upon receiving a response from my API, I retrieve a list of projects and aim to locate the one matching the ID provided in the URL parameter. A peculiar error ...

I'm encountering a barrage of errors while attempting to compile my React project. I'm completely stumped as to what they mean or where to even start in resolving them

Here is the error message: WARNING in ./node_modules/@ethersproject/abi/lib.esm/_version.js Module Warning (from ./node_modules/react-scripts/node_modules/source-map-loader/dist/cjs.js): Failed to parse source map from 'C:\Users\seana\N ...

Exploring the functionality of utilizing dual loops with v-for in Vue.js

I am facing an issue with my table code where I need to repeat it 6 times to match the day column above. I would like to use v-for and make use of a variable called "count" which represents the number of days. Can someone assist me with this task? <tabl ...

Parsing JavaScript within HTML using HTML DOM Parser is essential for understanding and manipulating dynamic web content

Currently, I am attempting to extract the download link for zippyshare files in PHP. The challenge I am facing is the need to access their JavaScript code, which I am struggling to do. This is the specific section of the page that I am trying to extract: ...

Despite the correct value being displayed in the console.log, the Textfield is not responding to the Reducer

I am currently working on a project to create a tool that can iterate through the pupils of a school class. In order to achieve this, I have implemented a text field in a react component that displays a value: <input className="form-control" onChange={ ...

When you click on the Admin Panel Side menu, the page refreshes instead of expanding the menu item

I have encountered a strange problem with the AdminLTE admin panel template that I am using in my Angular 11 application. Everything is loading fine with the menu items, but when I click on an item, instead of expanding the group, the page refreshes. Here ...

Looking for assistance with navigating through this URL using Python (requests, beautifulsoup, or selenium) or Javascript (node js, puppeteer)?

While attempting to gather data, I encountered an interesting pagination challenge on the following URL: My expertise in Web Scraping was put to the test as this website implemented a unique JavaScript-driven pagination. For the initial 5 pages, it simply ...

Getting the URL of a CSS background image in NodeJS and Express: A step-by-step guide

I've recently learned that using getComputedStyle in a Node environment is not possible due to it being a browser-specific behavior. Despite this, I am still interested in retrieving all background image URLs within Node and downloading them as shown ...

"Encountered an Unspecified Variable Error in executing document

Every time I open my Chrome console, it keeps showing an error message saying "toggleOnlyRelatedPosts is not defined". The script I'm working on doesn't seem to be functioning properly. I've added so many variables that I now feel lost and o ...

Unable to utilize Stats.js with @angular/cli version 1.4.4

Attempting to utilize @types/stats with @angular/cli following the guidance at https://github.com/angular/angular-cli/wiki/stories-third-party-lib. However, encountering a tslint error when trying to import * as STATS from 'stats.js'. [ts] Modul ...

Objects of equal nature combine and sift through

I am looking to categorize objects based on their status ID and also retrieve data and CSR counts for each item. Each StatusName has multiple items: [ { "StatusId": 2, "StatusName": "ordered", " ...