Troubleshooting issue with applying hover effect to child divs

How come when I hover over one of the child items in my parentDiv, the background of the last childDiv changes no matter which child I place my mouse on?

for (let i = 0; i < Number(height); i++)
    {
        for (let j = 0; j < Number(width); j++)
        {                               
            var childDiv = document.createElement("div");
            childDiv.className = "childDiv";
            childDiv.style.backgroundColor = "#e6e6e6";
            childDiv.id = `${i};${j}`
            childDiv.onclick = () => childDiv.style.backgroundColor = "black";
            childDiv.onmouseenter = () => childDiv.style.background = "#cccccc";                
            childDiv.onmouseleave = () => childDiv.style.background = "#e6e6e6";
            parentDiv.appendChild(childDiv); 
        }           
    }

Answer №1

Modify the variable declaration from var to let:

let childDiv = document.createElement("div");

You can view a functional example here. Additionally, for more information on the variance between var and let, it essentially boils down to this: using var childDiv creates the variable once during the first iteration, making it visible outside of for loops. On the other hand, with let childDiv, the variable is created separately on each iteration within the loop and is not accessible outside of it. Arrow functions ()=>{} utilize the value of childDiv set in the last iteration after the loop execution when declared with var; whereas, declaring with let creates a new instance for each iteration.

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

What is the best way to find the product of each object in an array by the corresponding values in another array?

Searching for a solution to an issue I encountered while working on an assignment. The problem can be illustrated as follows: var arrOfObj = [{a:10 },{a:20},{a:30}, ......] var arrToMultiply = [2,4,6, .....] The expected result const result = [{a:10,resul ...

Different option for key press identification

My JavaScript skills are still at a beginner level and I've come across a bug that's causing me trouble. The issue is with keyCode not working on mobile devices (Chrome). It seems that mobile devices do not support keyCode. I think I could use ...

Having trouble loading xml/xsl files on IE11? Consider enabling compatibility mode to ensure smooth rendering on your xml/xsl page

On my website, I have a page that displays XML from an XSL document. Strangely, it works perfectly on IE8 but not on IE11 - the page appears blank even though the XML is present when viewing the source. Interestingly, if I enable compatibility mode for the ...

Utilizing Nuxt3's auto-import feature alongside Eslint

I'm having trouble finding an eslint setup that is compatible with Nuxt3's auto-import feature to prevent no-undef errors. I have tried various packages like @antfu/eslint-config, plugin:nuxt/recommended, @nuxt/eslint-config, @nuxtjs/eslint-confi ...

Discovering the method for keeping track of file changes and executing find-replace operations without registering it as an event within the monitored file

I am confused about why the output displays two lines when typing 'fizbuzz' into the test.txt file. I understand that it is performing a find and replace operation, but how can I avoid it being triggered by the watch function? const watch = requ ...

Extract a specific pattern from a string using Javascript

Currently, I am attempting to extract a specific string from a tag in javascript using the following code: document.querySelector('.title h2').textContent However, when I execute this code, I am getting a result that includes unnecessary double ...

In React JSX, what is the best approach for printing a substring?

I am facing an issue with dividing two variables in my React component. I need to display the result to only one decimal place, so I decided to use the substring method like this: <div className="col-md-8"> {(total_star / total_user).toString ...

Steps to fix issues with Cross-Origin Read Blocking (CORB) preventing cross-origin responses and Cross Origin errors

var bodyFormData = new FormData(); bodyFormData.set("data", "C://Users//harshit.tDownloads\\weather.csv"); bodyFormData.set("type", "text-intent"); //axios.post("https://api.einstein.ai/v2/language/datasets/upload", axio ...

What is the best way to extract data from an array of objects in a JSON response?

I am currently exploring the utilization of API's in React. Right now, I am developing a search input feature for country names using the Rest Countries API. The data is being pulled from . However, I am facing a challenge in handling this data as it ...

What is the process for establishing the default type for an Activity Entity in Microsoft Dynamics?

Currently in the process of restructuring a portion of script code associated with the Fax Activity Entity within Microsoft Dynamics. Within the script code, the following can be found: document.getElementById("regardingobjectid").setAttribute("defaulttyp ...

Unable to locate the JavaScript/jQuery key

Struggling with a dictionary in JavaScript being passed to a function in Django. Despite the key existing, I'm getting an error saying 'key message not found'. As a newbie in Javascript and JQuery, I must have made a simple mistake somewhere ...

Tips for incorporating a value within the AngularJS select function

Having an issue with passing a list value in the html select method using AngularJS. Here is my code: app.js $scope.subcategory = function() { var query = "SELECT unit FROM Length;"; $cordovaSQLite.execute(db, query).then(function(res) { ...

Encountered an error when trying to access the 'modules' property of undefined in the /node_modules/bindings/bindings.js file while working with electron and setting up

1. npm install -g node-gyp 2. npm install serialport -S 3. npm install electron-rebuild -D 4. ./node_modules/.bin/electron-rebuild.cmd and after that, the rebuild process is completed. When I execute the command: npm run electron:serve, I encounter an ...

Struggling to connect the array of objects from the .ts file with the template (.html) in Angular

Inside this .ts file, I am populating the "mesMenus" array that I want to display in the .html file: export class MenusComponent{ mesMenus= new Array<Menu>(); constructor(private gMenuService:GestionMenuService){ this.gMenuService.onAdd ...

Issue with kendo grid not properly saving recently added data

Unexpected Grid Behavior: Adding a new record Pressing the update button in the grid for the newly added row Cancelling before saving After completing the above actions, the newly added row disappears. View js fiddle example <!DOCTYPE html> <h ...

Tornadofx highlight selected row with CSS

I am attempting to modify the background color of a selected row and apply the same change to a listview. When I use cell{backgroundColor += Color.BLACK}, it successfully changes the color, but it does not retain the selection color as intended.I have al ...

Rearranging div placement based on the width of the screen

I am currently working on building a responsive website and I need two divs to switch positions depending on the screen width, both on initial load and when resizing. Despite my efforts in researching and trying various options, I have not been successful ...

Why does CSS respect height:auto for relative positioned parent elements but not width:auto?

Although CSS position properties may seem simple at first, when building a layout, tons of weird edge cases can come out of nowhere. One thing that I always overlooked was using height: auto or width: auto. To gain a better understanding, I stumbled upon ...

Global error handling for URQL GraphQL mutation is a critical aspect that needs to be effectively implemented

Here's the technology stack I'm using: react v17.0.2 graphql v16.8.0 graphql-ws v5.14.0 urql v4.0.5 I rely on Hasura Actions to interact with a REST API and am in need of a solution for handling global errors for all mutations. For instance, I ...

Looking for a SSR Component to Choose Dates?

In the process of designing a landing page, I encountered a challenge with incorporating a date picker feature. My goal is to have users select a date and then be redirected to another page upon clicking a button. The technology stack includes NextJS where ...