Major Technical Issues Plague School-wide Celebration

In my JavaScript code, I am creating a 16x16 grid of divs. Each div should change its background color from black to white when the mouse enters (inherited based on a common class).

However, I am facing an issue where all the divs change color simultaneously when hovered over. Instead, each div should change its own color individually.


I suspect that all events are referencing the final div under the "squares" class, causing this unexpected behavior. I need help in making each event reference its respective div.

SNAPSHOT https://i.sstatic.net/oKmWW.png

CODE

//GRID CREATION (30x30)
var container = document.getElementById('container');
var size = 30;

//Row Creation (30)
for(j=0; j < size; j++) {
    var row = document.createElement('div');
    row.classList.add("row");

    //Square Creation (30 per Row)
    for(i=0; i<size; i++) {
        var square = document.createElement('div')
        square.classList.add("square");

        //div background-color changes on mouse-enter   
        square.addEventListener('mouseenter', () => { 
            this.square.style.background = 'white';
        });

        row.appendChild(square);
    }
    container.append(row);
}

Answer №1

Encountering this.square in your event listener without any other reference to it may seem odd. It's possible that you initially attempted square.style.background, which didn't work due to the concept explained in JavaScript closure inside loops – simple practical example. You then tried correcting it with this.style.background = 'white';, but facing issues because of an arrow function, leading you to try troubleshooting with this.square...?

In any case, consider using a non-arrow function to ensure that this refers to the element to which the event listener is attached instead of being the same as the outer this:

square.addEventListener('mouseenter', <b>function ()</b> { 
    <b>this</b>.style.background = 'white';
});

Alternatively, opt for declaring variables with let (which you must have access to since you were employing an arrow function) and make use of square:

//GRID CREATION (30x30)
let container = document.getElementById('container');
let size = 30;

//Row Creation (30)
for (let j = 0; j < size; j++) {
    let row = document.createElement('div');
    row.classList.add("row");

    //Square Creation (30 per Row)
    for (let i = 0; i < size; i++) {
        let square = document.createElement('div');
        square.classList.add("square");

        //div background-color changes on mouse-enter   
        square.addEventListener('mouseenter', () => { 
            square.style.background = 'white';
        });

        row.appendChild(square);
    }
    container.append(row);
}

Additionally, declarations for j and i appeared to be missing. Enabling strict mode is recommended, and it's advised to avoid using var to prevent such issues from occurring.

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

Is there a way to dynamically import images in Next JS without having to place them in the public folder?

Currently, I am developing a textbook website in which authors contribute textbook folders containing markdown files and images: textbooks ├───textbook-1 │ ├───images │ └───markdown-files └───textbook-2 ├── ...

Issue in d3.js: bisector consistently returning zero

http://jsfiddle.net/rdpt5e30/1/ const data = [ {'year': 2005, 'value': 771900}, {'year': 2006, 'value': 771500}, {'year': 2007, 'value': 770500}, {'year': 2008, 'value&apos ...

What can be done to ensure that the a href tag is functioning as clickable?

Having an issue with my HTML and CSS code for a notification dropdown box. I am unable to click the tag, even after attempting to use JavaScript. Can't seem to figure out what's causing this problem. Any advice on how to make the tag clickable? ...

Ways to implement StackNavigator along with Redux?

Is there anyone who can assist me in integrating StackNavigator and Redux? It seems straightforward, but I'm encountering issues. index.ios.js import React from 'react' import { AppRegistry } from 'react-native' import { Provi ...

What is the best way to retrieve an array that was created using the useEffect hook in React?

Utilizing the power of useEffect, I am fetching data from two different APIs to build an array. My goal is to access this array outside of useEffect and utilize it in the return statement below to render points on a map. However, when trying to access it ...

What is the best method for importing Bootstrap into SvelteKit?

I am currently working on a SvelteKit website. I have integrated Bootstrap 5 into my project by adding it to the app.html file provided by the SvelteKit Skeleton starter project: <!-- Bootstrap styles and javascript --> <link rel="stylesheet ...

Ways to extract single JSON entities from a consolidated JSON structure

I am facing a challenge with parsing multiple JSON objects within a single large JSON object. Currently, the entire JSON object is being stored as one entity, but I need to parse and store them separately in MongoDB. Below is the code snippet I am using. ...

Enhance your data retrieval from XPATH using Javascript

Here is the layout of an HTML template I am working with: <div class="item"> <span class="light">Date</span> <a class="link" href="">2018</a> (4pop) </div> <div class="item"> <span class="light">From</sp ...

Learn the best method for accessing and utilizing an existing file effortlessly

As a newcomer to PHP, I have successfully learned how to upload a file from a list using the following code: var file = e.target.files[0]; alert(file); This code returns an [object File], indicating that the file has been uploaded. Now, my question is: ...

The automatic form completion feature in JavaScript failed to function

The last 2 rows starting from "request.done...." are not functioning correctly. Nothing happens when these lines of code run, even though everything else works perfectly Here is the script I am using: $(document).ready(function () { $('#retriev ...

MUI Error: Incorrect prop provided to menu item

I am encountering an issue with a React component that generates a list of elements, each containing a button to open a menu. The problem is that the props being passed to each menu are incorrect; they always reflect the props of the last element in the ...

Differences between Cypress and JQuery objects, and the significance of the cy.wrap function

Currently diving into cypress and experimenting with various testing methods. If anyone could lend me a hand with the following inquiries: 1. I've come to understand that most cypress objects utilize jQuery objects for DOM operations, but what sets t ...

Tips for adjusting a pre-filled form?

When a form is rendered by onClick from a component, it loads with values. I want to be able to edit these current values and then perform an update operation. Here is the link to the sandbox: https://codesandbox.io/s/material-demo-forked-e9fju?file=/demo ...

Having trouble establishing an HTTPS connection with a Node.js server

After connecting to my server through the console without any errors, I encountered an issue in Chrome where it displayed a message stating This site can’t provide a secure connection local host uses an unsupported protocol. Here is the code snippet: im ...

Creating a SWT paint event upon initializationIf you want to trigger a SWT

Currently, I am working on a SWT application that organizes image files by renaming them for sorting purposes. While this method may seem unpolished, the sorted-by-name files are essential for a subsequent step that cannot be altered. Although the UI is a ...

Detecting repeated keys in a query for a REST connector in loopback

Can anyone help me figure out how to duplicate parameters in a loopback REST connector query? Here's the code snippet I'm working with: details: { 'template': { 'method': 'GET', 'debug': tr ...

Maximizing Efficiency: Sending Multiple Responses during computation with Express.js

Seeking a way to send multiple responses to a client while computing. See the example below: app.get("/test", (req, res) => { console.log('test'); setTimeout(() => { res.write('Yep'); setTime ...

The image will remain hidden until it is fully loaded and ready to be displayed

I am currently working on a script that involves displaying a loading icon until an image is fully loaded, at which point the loading icon should disappear and the image should be shown. Unfortunately, my current code is not working as intended. Here is a ...

Dealing with transformed data in AngularJS: Best practices

Scenario I have a dataset structured like: [{ xRatio: 0.2, yRatio: 0.1, value: 15 }, { xRatio: 0.6, yRatio: -0.3, value: 8 }] I need to convert this data into absolute values for display in a ng-repeat. However, when I attempt to do so usin ...

Unraveling the Mystery of Code Organization, Exploring the Depths of Polym

Although I am new to the Python language, I have experience with a variety of programming languages including C++ and Java. I recently began learning Python due to a requirement in my Computer Science course at school. Despite my extensive use of other pro ...