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

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

Using namespaces in Rails to encapsulate CSS styles

Is there a way to add namespaces to CSS within a Rails project? I have two pre-defined CSS files and two application layouts. I want the first layout to use one CSS file, and the second layout to use the other. However, both CSS files have styles for the ...

While iterating through a dynamically generated JSON data array, omitting the display of the ID (both title and value) is preferred

I am working with a JSON data Object and using $.each to dynamically retrieve the data. However, I want to display all values except for one which is the ID. How can I achieve this and prevent the ID from being displayed in the HTML structure? Thank you. ...

Is it possible to utilize an ng template within one component and then reference its template in another HTML file?

I'm experimenting with using ng-template in a separate component and referencing it in other parts of the html. Is this possible? I've tried different approaches but seem to be missing something. Can you help me understand where I might be going ...

Issue with accessing data in React Admin Show Page using useRecordContext() function leads to undefined return

Within a basic RA application, I am attempting to showcase an item known as a "card" utilizing a Show Page. The fields—specifically id and title—are being presented correctly. Nevertheless, the useRecordContext() hook is consistently returning undefin ...

ID could not be retrieved from the checkbox

I am facing an issue with my HTML checkboxes. The ids are generated from an angular ng-repeat, but when I try to collect the id for use, it always returns as undefined. $("input:checkbox.time-check-input").each(function () { var ruleUnformatted = ""; ...

Upon the initial rendering, Next.js obtains access to the query { amp: undefined }

When using Next.js 9.3, I encountered an issue where I needed to access the query on initial render and pass the result of the query to next/head in order to change the title and description of the page. The component is receiving the query from the useRo ...

Utilizing HTTPS for OpenWeatherMap API in JavaScript encounters obstruction

I'm currently working on a project with free code camp where I am attempting to create a weather app using the OpenWeatherMap API. However, I have encountered an issue. My project needs to be submitted on Codepen and use HTTPS for geolocation. Due to ...

Removing CSS from a Link in react-router-dom

My attempt to create unique divs for different pages using the code in my home.js didn't go as planned. <Link to="Subject1"> <Product title="The Lean Startup" image="https://images-na.ssl-images-amazon.co ...

Effect on Label in WordPress Contact Form 7 When Input Field is Populated

Currently, I am attempting to achieve the floating label effect on Contact Form 7 and have encountered an issue. Although I have successfully implemented the label effect on input:focus, I am struggling to make it persist once text has been entered and foc ...

What is the reason behind certain websites not displaying a .php extension at the end of their file names?

There are times when I notice that a website's URL is structured like this: www.website.com/index.php while other times it appears like this: www.website.com/index/ What is the reason for the absence of a .php or .html extension in the second URL? ...

Use CSS properties to isolate and extract the logo from the Sprite image

If we have a sprite image, like the StackOverflow sprite, and CSS properties like: background-position: 0px 0px; width: 250px; height: 61px; We can use the Chunky PNG library to crop out a specific part of the sprite. However, some websites use negative ...

Automatically refresh a table within a webpage with updated database information without the need to manually refresh the

I'm a beginner in PHP and AJAX. The issue I am currently encountering is displaying a table on a JSP page and wanting to auto-update the table without refreshing the page every 10 seconds. I retrieve values from a database using a PHP page Below is t ...

Overlap bug with Flash content

In both Google Chrome (16.0.912.75 m) and Safari (5.1.1), I am encountering the well-known flash / html overlay issue. Despite setting the wmode attribute to transparent as suggested here and here, along with trying opaque, the problem persists. Following ...

How to Retrieve an Array from a Promise Using Angular 4 and Typescript

I am encountering difficulties when trying to store data from a returned promise. To verify that the desired value has been returned, I log it in this manner: private fetchData() { this._movieFranchiseService.getHighestGrossingFilmFranchises() ...

If viewed on a mobile device, separate the array (indexed list) into two rows

Currently, I am working on my Ionic project where I am trying to implement an indexed list horizontally instead of vertically. While the list looks good as it is now, I want to make sure it supports smaller screen devices too by splitting the list into two ...

Tips on effectively rendering child components conditionally in React

My components currently consist of an AddBookPanel containing the AddBookForm. I am looking to implement a feature where the form is displayed upon clicking the 'AddBookButton', and hidden when the 'x' button (image within AddBookForm c ...

JavaScript / AngularJS - Efficient Boolean Switching

My group of Boolean variables can toggle other variables to false when set to true. I am looking for a clean pattern for this approach, especially since the number of boolean variables may increase. angular.module("app", []) .controller("controller", ...

Step-by-step guide for embedding a Big Commerce website into an iframe

Can a website be opened inside an iframe? If not, is it possible to display a message like 'page not found' or 'this website does not allow data fetching in iframes'? <!DOCTYPE html> <html> <body> <h1>Using the ...

Storing user information in Angular after login and implementing JWT authentication

Is it advisable to save any user information other than JWT in local storage or cookies after a successful login? (The user profile object is already saved and encrypted in the JWT payload sub-part.) I need the user profile object ready before initializing ...