What is the best way to include a click event in a newly created node by using cloneNode and appendChild within a forEach loop?

I am striving to create an infinite imageview feature.

Although I have managed to implement the same movement and add new elements using cloneNode and appendChild, the button in the new element does not respond to the click event as expected.

How can I ensure that the new elements also have the same click event functionality?

let listMarginTop = 70;
let listMarginLeft = 40;
let list = document.getElementById('firstLine');
let lists = document.getElementsByTagName('li');
let listsArr = [...lists];
let z = 10;
let transDelay = 1;
let xBtn = document.getElementsByClassName('xBtn');
let xBtnArr = [...xBtn];

for(let i = 0; i < listsArr.length; i++)
{
    listsArr[i].style.transition = 'all 0.5s linear ' + transDelay + 's';
    transDelay -= 0.1;
    listsArr[i].style.zIndex = z;
    z--;
    listsArr[i].style.marginTop = listMarginTop + 'vh';
    listsArr[i].style.marginLeft = listMarginLeft + 'vw';
    listMarginTop -= 6;
    listMarginLeft -= 6;
}
let lastChildMarginTop = 12;
let lastChildMarginLeft = -20;
xBtnArr.forEach((x) => {
    x.addEventListener('click', () => {
        let copyWindow  = x.parentElement.parentElement.cloneNode(true);
        x.parentElement.parentElement.style.opacity = '0';
        copyWindow.style.marginTop = parseInt(list.lastChild.style.marginTop) - 6 + 'vh';
        copyWindow.style.marginLeft = parseInt(list.lastChild.style.marginLeft) - 6 + 'vw';
        copyWindow.style.zIndex = z;
        z--;
        lastChildMarginTop -= 6;
        lastChildMarginLeft -= 6;
        list.appendChild(copyWindow);
        let listChildArr = [...list.childNodes];
        listChildArr.forEach(win => {
            win.style.marginTop = parseInt(win.style.marginTop) + 6 + 'vh';
            win.style.marginLeft = parseInt(win.style.marginLeft) + 6 + 'vw';
        })
        xBtn = document.getElementsByClassName('xBtn');
        xBtnArr = [...xBtn];
        console.log(xBtnArr);
    })
})
* {margin: 0; padding: 0; border: 0;}
ul
{
    list-style-type: none;
    position: relative;
}


.rightMain
{
    height: 100vh;
    flex: 7;
    flex-wrap: wrap;
    overflow: hidden;
}

#container
{
    position: absolute;
    z-index: 3;
}

ul li
{
    margin-top: -10vh;
    margin-left: -10vw;
    position: absolute;
}

.showWindow
{
    width: 25vw;
    height: 25vh;
    border: 1px solid black;
    background-color: white;
}

.showWindow button
{
    margin: 0.5vw 0.5vw 0;
    width: 1vw;
    height: 1vw;
    border-radius: 50%;
    border: 1px solid black;
    background-color: white;
    cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id='rightMain' className='rightMain'>
            <div id="container">
                <ul id='firstLine'>
                    <li>
                        <div className='showWindow'>
                            <button className='xBtn'></button>
                            <button></button>
                        </div>
                    </li>
                    <li>
                        <div className='showWindow'>
                            <button className='xBtn'></button>
                            <button></button>
                        </div>
                    </li>
                    <li>
                        <div className='showWindow'>
                            <button className='xBtn'></button>
                            <button></button>
                        </div>
                    </li>
                    <li>
                        <div className='showWindow'>
                            <button className='xBtn'></button>
                            <button></button>
                        </div>
                    </li>
                    <li>
                        <div className='showWindow'>
                            <button className='xBtn'></button>
                            <button></button>
                        </div>
                    </li>
                    <li>
                        <div className='showWindow'>
                            <button className='xBtn'></button>
                            <button></button>
                        </div>
                    </li>
                    <li>
                        <div className='showWindow'>
                            <button className='xBtn'></button>
                            <button></button>
                        </div>
                    </li>
                    <li>
                        <div className='showWindow'>
                            <button className='xBtn'></button>
                            <button></button>
                        </div>
                    </li>
                    <li>
                        <div className='showWindow'>
                            <button className='xBtn'></button>
                            <button></button>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
</body>
</html>

Answer №1

In order to solve two issues here -

  1. The HTML elements do not have a className attribute. You need to update it to class for each element so that the correct class is accepted and you can accurately select DOM Nodes using the getElementsByClassName() method.
  2. If your goal is to create an infinite image view, instead of attaching numerous event listeners to individual buttons, consider utilizing Event Delegation. To learn more about Event Delegation, check out this resource here. Implementing this technique will enhance your application's performance.

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

Troubleshooting common issues with PHP's simple HTML DOM parser

I've encountered an issue while working on a scraper for a website that involves crawling through links. The error message I'm receiving is as follows: PHP Fatal error: Uncaught Error: Call to a member function find() on null in D:\Projekti ...

Struggling with handling numbers and special symbols in the Letter Changes problem on Coderbyte

Hello I have been struggling to find a solution for my current issue. The problem lies within an exercise that requires changing only alphabetical characters, but test cases also include numbers and special characters which are being altered unintentionall ...

Refreshing the browser does not load the Angular2 component and instead shows a 404 error

During my exploration of Angular 2, I developed a basic restaurant management application. Now, I am delving into more advanced techniques such as creating an app bundle, minification, and optimizing the application. The authentication component in my app ...

What is the best way to calculate the total of multiple columns using JavaScript and jQuery?

I am looking to modify my table that has two different columns in order to calculate the sum of both. Currently, I can only add up one column using JavaScript, and duplicating the JS code with different value names for the second column is not ideal. How c ...

The behavior of React's SetState in an event handler varies when using mocked data versus data fetched from an API

Currently, I am replicating the same scenario with identical code in two different situations. With mocked data With data fetched from an API 1) The case with Mocked Data => https://codesandbox.io/s/select-demo-0e90s is functioning as expected The m ...

Tips for eliminating unnecessary white space using CSS

https://jsfiddle.net/38h8acaq/ Is there a way to eliminate the white space on the left of the first tab and between the tabs and the content? Despite adding several margin:0px; lines to the CSS, none seem to be effective in removing the unwanted whitespac ...

Is there a more efficient method for writing my jQuery code that follows a step-by-step approach?

I have developed a step-by-step setup process that guides users through various sections. Instead of using separate pages for each step (like step1.php, step2.php, etc.), I have all the code contained in one page named setup.php. This is achieved by utiliz ...

Building New Web Pages with Express in Node.JS

I want to dynamically generate a new page on Node.JS with Express upon user form submission. Here is my initial approach, but it's not working as expected: var app = require('express')(); var server= require('http').createServer(a ...

Adjusting the height of table rows based on the content within the <td> element

I am facing a challenge with a table that includes rows with 2 columns - one for images and the other for text. The issue arises when resizing large images in one column, causing the row to take its height from the image cell rather than the text cell. Sin ...

Having difficulty locating any content within the return element in JSX

I'm relatively new to React and JSX and currently working on creating a button that, when clicked, should trigger a dialog box to appear. Within this dialog box, there should be a table with three columns: name, status, and exception error, all repres ...

How to showcase arrays using a variety of vibrant colors

In my web application, users input a paragraph and the backend system scans it to identify hard and very hard sentences. My goal is to display the entire paragraph with these difficult sentences highlighted in yellow and red backgrounds respectively, while ...

Storing an HTML page in a PHP variable, parsing it, and displaying it correctly

I am currently using the simple_html_dom parser to extract information from an HTML page. After making some modifications, I would like to display this content on my own page. $page = file_get_html($url); foreach($page->find('div#someDIv') as ...

Retrieve the average value from a SQL table and showcase it on an HTML page

I have scoured through multiple forums in search of a solution to my problem without success. I am in need of assistance. I am trying to calculate the average of numbers from a SQL database and show this average on an HTML page. My tools include Flask, Py ...

We're sorry, but the package path . cannot be found within the package's exports

No connection with Firebase due to error(s) in code. File: firebase.js Code: import * as firebase from "firebase" const firebaseConfig = { apiKey: "***", authDomain: "***", projectId: "***", storageBucket: ...

Eliminating render-blocking CSS in PageSpeed - one stylesheet at a time

Currently, I am testing the best optimization practices for front-end development. As part of this process, I have utilized gulp and npm to merge and minify my CSS and JS files into a single all.min.css and js.min.css file. Upon analyzing my website using ...

Do I have to update my application's Node.js version from v0.10 to either v4 or v6?

My application relies on Node.js, Swagger, Express, and MongoDB. Currently, I am using an outdated version of Node.js v0.10.x. While I am concerned about the future usage of my app in 1.5 years, I find it challenging to devote time to upgrading to a newe ...

CSS: Placing items within an ng-for loop utilizing the "fixed" position property

<ul class="nav nav-pills nav-stacked" style="list-style: none"> <li *ngFor="#el of dragZoneElems; #idx = index"> <h4 style="position: fixed; top:'idx'*10" [dragResponder]="el">{{el.first}} {{el.last}}</h4& ...

Exploring Java Programming with HTMLEditorKit

Here is my source code: I am trying to change the font color using only CSS. This is how I am inserting HTML: <span class="tag1">I love <span class="tag2">apple</span></span><span class="tag2"> pie</span> When using ...

"Learn how to properly load the style.css file from the root directory into your WordPress page.php and single.php files

Having an issue with my WordPress theme. The style.css stylesheet does not seem to be loading in the page.php contents. I noticed that when I add <div class=w3-red"> <button class="w3-btn w3-red"> and other related codes while editing a post in ...

Enhance the functionality of the custom transaction form in NetSuite by incorporating new actions

I'm currently working on incorporating a new menu option into the "Actions" menu within a custom transaction form in NetSuite. While I can successfully see my selection in the Actions Menu on the form, I'm running into an issue with triggering th ...