How do I access the divs and color them when the mouse is hovered over them. They are created inside a bigger container when the user inputs a value and i cannot access them by another fucntion.
HTML
<body>
<div>
<div id="outer_container">
<div id="container"> </div>
</div>
<div id="user_input_container">
<input type="color" class="user_input" name="" id="colour_picker" value="#000000">
<button class="user_input" id="rainbow">Rainbow</button>
<div>
<div>
<input class="user_input" type="range" min="2" max="100" value="16" name="options"
id="grid_range">
</div>
</body>
Javascript
let container = document.getElementById(`container`);
function createGrid(number) {
totalNumber = number * number;
while (container.hasChildNodes()) {
container.removeChild(container.firstChild);
}
for (let i = 0; i < totalNumber; i++) {
let gridSquare = document.createElement("div");
gridSquare.classList.add("grid_square");
let cellwidth = container.clientWidth / number + `px`;
let cellheight = container.clientHeight / number + `px`;
gridSquare.style.width = `${cellwidth}`;
gridSquare.style.height = `${cellheight}`;
container.appendChild(gridSquare);
}
}
document.addEventListener("DOMContentLoaded", () => {
createGrid(range.value);
});
let range = document.getElementById(`grid_range`);
range.addEventListener(`change`, () => {
createGrid(range.value);
});
let color = document.getElementById(`colour_picker`);
What I did was just add an eventlistener()
in the createdGrid()
function that takes the value from "color"
picker, but really not able to access the divs inside and get them colored by and oustside fucntions specifically for coloring.
The eventlistener()
below is what I added inside the for()
loop of createdGrid
function.
gridSquare.addEventListener("mouseover", (event) => {
event.target.style.backgroundColor = color.value;
});
Thanks!
2
Answers
To do what you require, add a
mouseenter
andmouseleave
event handler to thegridSquare
elements you create within each loop. One event adds thebackground-color
and the other removes it.To achieve the functionality of changing the color of the divs when the mouse is hovered over them based on the color selected by the user, you can create a separate function for coloring the divs.