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

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

Before you start interactivity in three.js, you will be presented with a classic

Recently, I incorporated a 3D WebGL viewer into my website, but I encountered a minor problem. Although everything functions properly and I am able to manipulate the object, there is a brief moment of a black screen upon loading the page before moving the ...

Tips for safely executing an SQL query with electron.js

I have a new project where I need to interact with an SQL database on the local network, but it's not located on the same system I'm working on (not SQLExpress). So far, I've figured out how to collect user input on a webpage and send that ...

Make sure that the parent element is only visible once all of its child elements have

As a newcomer to the world of react, I am facing some challenges. I have created a form in react which includes a dropdown. To ensure reusability across multiple pages, I decided to turn this dropdown into a component that is responsible for fetching all n ...

What steps can I take to resolve the issue of the Error value not being iterable?

I encountered an issue in my table where I get the error message value is not iterable when there is no value to iterate through. How can I handle this error in my code? Snippet of Code: if (null != data && data) { data = data.map((item) => ...

Using React to fetch data and then mapping it inside a function

I am facing an issue where I need to make a request for each item in the MAP, but I want to ensure that I wait for the response before moving on to the next object. Currently, my code is sending out all the requests simultaneously, causing the Backend to c ...

The collaboration between delegate and :not(.myClass) is ineffective

How can I select all ul li items that do not have the .roundabout-in-focus class? $("ul").delegate("li.roundabout-in-focus", "click", function() { $(this).css({position:'absolute',height:'300px',width:'400px',le ...

Implement a callback function for unchecked checkboxes on change

Currently, I am working with a gridview that includes a checkbox field. My goal is to use jQuery to create a function that activates when an unchecked checkbox is checked. function clickAllSize() { alert("helloy"); } $(document).ready(function () { ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

Utilizing event delegation for JavaScript addEventListener across multiple elements

How can I use event delegation with addEventListener on multiple elements? I want to trigger a click event on .node, including dynamically added elements. The code I have tried so far gives different results when clicking on .title, .image, or .subtitle. ...

Angular has the capability to rewrite URLs in CSS, providing a unique way

An issue arises in Angular when using a base set and html5mode with SVGs. This causes things like filter: url(#url) to be rewritten as filter: url(/base/#url). https://github.com/angular/angular.js/issues/8934 Disabling html5 mode and removing the base d ...

Creating JSON with PHP: Ensuring consistent keys in JSON output derived from PHP arrays

Is there a method to convert a PHP array (or any other similar PHP object) into JSON while maintaining identical keys for a JSON array? For example: {"categories" : [ {"key": "data1"}, {"key": "data2"}, {"key": "data3" } ] } It is worth noting that the ...

Discover and update values in JSON using JavaScript

Currently, I am working on generating graphs using d3.js with a JSON file as the input. My main challenge lies in parsing the date and time format for the x-axis. Below is the code snippet that I have attempted: d3.json('data/fake_users11.json', ...

Move to Fieldset Upon Link Click

Here's an example of what I have implemented so far here It's evident that this is not fully functional due to the PHP and jQuery integration. This demo is just a showcase of my progress. I am looking to create a functionality where clicking on ...

ReactJS aligns buttons to the right

I have been attempting to align a button to the far right without success. Here is what I have tried: <Button variant="contained" style={{display: 'flex', justifyContent: 'right'}} color="primary" className="float-right" onClick={ ...

Controller encountering JSON null data

I am currently working on a feature that allows users to send multiple email/SMS messages by selecting checkboxes. However, I am facing an issue where the data is not being passed correctly from my JavaScript function to the action method - all the data sh ...

I'm wondering how I can design a utility function within my Redux module that can extract a specific subset of read-only data from the current state

I am currently utilizing redux to create a "helper function" inside my redux module that is responsible for fetching filtered data from the state based on a specified index. This specific data will be used to generate a form consisting of inputs depending ...

The iframe came to a halt as soon as it was no

I am currently developing a live video website that utilizes third-party tools to play the videos. To simplify things, I have embedded all the components required for live video into a single HTML page. Here is how it looks: <iframe data-v-140cfad2= ...

The request to http://localhost:8080 from http//:localhost:3000 has been restricted due to CORS policy blocking access. This is due to the absence of the 'Access-Control-Allow-Origin' header in the

const fileStorage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "images"); }, filename: function (req, file, cb) { cb(null, uuidv4()); }, }); const fileFilter = (req, file, cb) => { if ( file.mi ...

Issue with AngularJS: Local storage not saving updated contenteditable data

My local storage implementation stops working when I attempt to incorporate contentEditable feature. Here is the link to the CodePen for reference: https://codepen.io/zanderbush/pen/WNwWbWe. Any assistance would be greatly appreciated. The functionality w ...

Dynamic parameterization of Angular form controls

I'm facing an issue with adding validators to a form where some controls are required only if a specific condition is met by another control. I initially created a custom validator function that takes a parameter to determine the requirement, but the ...