Unable to attach a javascript eventListener to a newly created element

I've utilized JavaScript to generate 625

<div class="box"><div>
elements and now I'm trying to attach an event listener to each box. The boxes are being created successfully, however, the listener does not seem to be working. Below is my complete code. Any help or suggestions would be greatly appreciated. Thank you!

<!DOCTYPE html>
<html>
<head>
    <title>Number AI | Machine Learning Technology</title>
    <style>
        .box-container{
            display: grid;
            width: 300px;
            height: 300px;
            border: 1px solid blue;
            grid-template-columns: auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto;
        }
        .box{
            width:10px;
            height:10px;
            border: 1px solid black;
            text-align: center;
        }
    </style>
    <script type="text/javascript">
        function initiateBox(){
            for (let i = 0; i < 625; i++) {
                let box = document.createElement("DIV");
                box.classList.add("box");
                document.querySelector('.box-container').appendChild(box);
            }
        };
        window.onload = initiateBox;
    </script>
</head>
    <body>
        <h2>Number AI</h2>
        <div class="box-container"></div>
        
        <script>
            document.querySelectorAll(".box").forEach(box =>{
                box.addEventListener("mouseover",function(){
                    box.style.backgroundColor = 'black';
                });
            });
        </script>
    </body>
</html>

Answer №1

There are a few strategies that can be used to achieve this effect:

  1. Utilize addEventListeners for both the 'load' and 'mouseover' events
  2. Implement event delegation so that you can create the boxes at any point after the container is available
  3. Consider using CSS hover as an alternative approach

Below is a sample script showcasing how event delegation can be implemented:

function initiateBox() {
  const container = document.querySelector('.box-container');
  for (let i = 0; i < 625; i++) {
    let box = document.createElement("div");
    box.classList.add("box");
    container.appendChild(box);
  }

  container.addEventListener("mouseover", function(e) {
    const tgt = e.target;
    if (tgt.classList.contains("box")) tgt.style.backgroundColor = 'black';
  });
};
window.addEventListener("load",initiateBox)
.box-container {
  display: grid;
  width: 300px;
  height: 300px;
  border: 1px solid blue;
  grid-template-columns: auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto;
}

.box {
  width: 10px;
  height: 10px;
  border: 1px solid black;
  text-align: center;
}
<title>Number AI | Machine Learning Technologhy</title>

<h2>Number AI</h2>
<div class="box-container">
</div>

Answer №2

If you're looking for a straightforward solution, you can add the event listener to box creation like this:

<!DOCTYPE html>
<html>

<head>
  <title>Number AI | Machine Learning Technology</title>
  <style>
    .box-container {
      display: grid;
      width: 300px;
      height: 300px;
      border: 1px solid blue;
      grid-template-columns: auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto;
    }
    
    .box {
      width: 10px;
      height: 10px;
      border: 1px solid black;
      text-align: center;
    }
  </style>
  <script type="text/javascript">
    function initiateBox() {
      for (let i = 0; i < 625; i++) {
        let box = document.createElement("DIV");
        box.classList.add("box");
        box.addEventListener("mouseover", function() {
          box.style.backgroundColor = 'black';
        });
        document.querySelector('.box-container').appendChild(box);
      }
    };
    window.onload = initiateBox;
  </script>
</head>

<body>
  <h2>Number AI</h2>
  <div class="box-container"></div>
</body>

</html>

For a more efficient approach, consider using event delegation as suggested by @mplungjan. Here's an example of how you can implement it:

<!DOCTYPE html>
<html>

<head>
  <title>Number AI | Machine Learning Technology</title>
  <style>
    .box-container {
      display: grid;
      width: 300px;
      height: 300px;
      border: 1px solid blue;
      grid-template-columns: auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto auto;
    }
    
    .box {
      width: 10px;
      height: 10px;
      border: 1px solid black;
      text-align: center;
    }
  </style>
  <script type="text/javascript">
    function initiateBox() {
      const boxContainer = document.querySelector('.box-container');
      for (let i = 0; i < 625; i++) {
        let box = document.createElement("DIV");
        box.classList.add("box");
        boxContainer.appendChild(box);
      }

      boxContainer.addEventListener("mouseover", function(event) {
        const target = event.target;
        if (target.classList.contains('box'))
          target.style.backgroundColor = 'black';
      });
    };
    window.onload = initiateBox;
  </script>
</head>

<body>
  <h2>Number AI</h2>
  <div class="box-container"></div>
</body>

</html>

Answer №3

In my opinion, the issue lies in the order of script execution where the second script runs before the box elements are added to the document, resulting in not finding any boxes. To solve this problem, you can include the eventListener within the initiateBox function that you have created:

function initiateBox(){
        for (let i = 0; i < 625; i++) {
            let box = document.createElement("DIV");
            box.classList.add("box");
            box.addEventListener("mouseover",function(){
                box.style.backgroundColor = 'black';
            });
            document.querySelector('.box-container').appendChild(box);
        }
    };
    window.onload = initiateBox;

If the intention is to change the background color on mouseover, using CSS hover would be a more efficient approach.

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 on employing the sendkeys function in selenium webdriverjs through promise chaining

Here is the coding snippet: driver.get(url).then(function(){ txtFnn = driver.findElement(webdriver.By.xpath(xpath)); return txtFnn; }).then(function(){ txtFnn.sendkeys("12345678"); }) Issue: An error occurred: Typ ...

Enhancing a React modal to enable user input for updating state variables

Is there a way to utilize user input from the page to dynamically create elements in a React.js application? In my app.js file, I have defined some constants at the beginning for mock data: const book1 = [ {id: uuid(), content: 'reflections&apos ...

Can a custom function be executed using setTimeout in Node.js?

I am currently facing an issue with stopping the execution of my code for 2 seconds so that all ongoing animations can finish. I am attempting to implement a delay using setTimeout in Node.js. Here is what I have tried: this.userActivity = function(a,b, ...

Leveraging ng-switch with ng-repeat in AngularJS to dynamically apply HTML based on conditions

I have a paginated list of video thumbnails that I want to showcase in a Bootstrap fluid grid. To achieve this, I am utilizing a nested ng-repeat loop to iterate through each list for pagination purposes. Within the inner loop, another ng-repeat is used to ...

Ways to create a table with columns from various fields obtained through an API call

Looking to preprocess data received from an API, the raw data is structured as follows: https://i.sstatic.net/a9Q2Z.png Desiring to dynamically generate a table with columns based on the fields task_name and saved_answers. It's important to note tha ...

What is the best way to access nested JSON data in Vue.js code demonstrated here?

How can I properly access the nested JSON data for stage.name provided in the example below? As shown in the template, my attempt to retrieve the stage name is not working. Using vue.js created() { url="http://{{ api_endpoint }}" fetch(url) ...

Scrolling to does not function properly with Material UI tabs

Looking for a solution to scroll to a specific div when clicking on a tab in Material UI Tabs using UseRef and ScrollTo. Check out the sandbox link here: https://codesandbox.io/s/exciting-sound-mrw2v Currently, when I click on Tab 2, I expect it to autom ...

Touch interaction operates differently than mouse movement

Imagine three neighboring divs, div1, div2, and div3. When I click on div1 and then move my mouse to div2, the mousemove event is triggered with div2 as the target. However, on mobile devices, if I tap on div1 (touchstart) and slide my finger to div2, the ...

Error parsing data in the $.ajaxSetup() function of JQuery

Currently, I am coding a program using jQuery. It was functioning perfectly in Firefox 3.5 until I upgraded to Firefox 4.0. Since then, the dreaded 'parsererror' keeps popping up and causing me quite a headache. I've pinpointed the exact pa ...

Php/JavaScript Error: Identifier Not Found

I've double-checked my code multiple times, but it still doesn't seem to be working properly. When the PHP runs, the browser console displays the following error: Uncaught SyntaxError: Unexpected identifier. I'm not sure if this is a si ...

Prevent Cross-Site Scripting attacks in Laravel by sanitizing user input, even when allowing HTML tags

What measures can be taken to protect against XSS attacks when a user is allowed to use HTML tags, such as in a textarea element? Avoiding the stripping or escaping of all tags complicates the situation and rules out the option of using {{ }}. It's a ...

Having trouble implementing the center edge effect in this CSS design

Looking for help with CSS to center the edges of a family tree design. Has anyone experience in working on styling family trees? *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .tree { ...

Despite passing JSLint, an unexpected end of input still occurred

It seems a bit absurd; despite my efforts, I'm unable to locate the syntax error. The Chrome debugger keeps indicating an "unexpected end of input" in line two. Any suggestions? $("head meta").each(function () { var content = JSON.parse(this.cont ...

Using AJAX to submit a PHP form without refreshing the page

Currently, I am facing an issue with my PHP and AJAX code for posting data without redirecting the page. Surprisingly, the script works perfectly on the login page but not on other pages. The main difference I observed is that the login page uses if (empty ...

Success is returned as AJAX error

My AJAX call is returning an error as Success instead of a JSON error from ASP.NET MVC. Can someone please advise on how I can resolve this issue? Thank you. [HttpPost] public JsonResult Register(int EventID) { try { ...

What is preventing the clickHandler from properly updating the state?

My goal is to dynamically change the background image based on the active button clicked. Although the clickHandler correctly identifies the button id, the state fails to update as expected. Can you help me spot what I may have missed? import React, { Com ...

Leveraging Gatsbyjs to Integrate GraphQL Data with Material UI Library

Just starting out as a Frontend Developer and currently learning Gatsbyjs along with the Material UI library. I'm working on creating a new page using the Material UI Gatsby Starter code available here. However, I've encountered an issue when tr ...

Improved method for retrieving a subtask within a personalized grunt task?

As someone who is just starting out with Grunt and has only created a few custom grunt tasks, I've come up with what might be seen as an unconventional solution for traversing the initConfig to subtasks. My approach involves putting together a regex a ...

Guide on converting AS3 to HTML5 while incorporating external AS filesAlternatively: Steps for transforming AS

I've been given the challenging task of transforming a large and complex Flash project into html5 and javaScript. The main stumbling block I'm facing is its heavy reliance on external .as files, leaving me uncertain about the best approach. Most ...

Eliminate the Jquery Combobox

I've implemented the Jquery Combobox on my website /*! * Combobox Plugin for jQuery, version 0.5.0 * * Copyright 2012, Dell Sala * http://dellsala.com/ * https://github.com/dellsala/Combo-Box-jQuery-Plugin * Dual licensed under the MIT or GPL V ...