I am trying to create a mouseover event that turns divs blue when I hover over them. I am looping over each div with forEach and expect it to turn blue when hovered over. However, the code is not working at all. I have determined that the nodelist has a length of 0, but I am not sure why that is. I want it to stay blue even after I stop hovering over it, which is why I am using js.
var form = document.getElementById("inputForm");
var clearButton = document.getElementById("clear");
var input = form.querySelector("input");
//Starts function that does everything
form.addEventListener("submit", function(e) {
//Prevents browser from refreshing on submit
e.preventDefault();
input.disabled = true;
var boxInput = input.value;
var gridContainer = document.getElementById("gridContainer");
console.log(boxInput);
for (var i = 0; i <= boxInput * boxInput - 1; i++) {
//Creates a certain number of rows and columns based on user input
gridContainer.style.gridTemplateColumns = `repeat(${boxInput}, 1fr)`;
gridContainer.style.gridTemplateRows = `repeat(${boxInput}, 1fr)`;
var div = document.createElement("div");
console.log(div);
div.className = "grid";
gridContainer.appendChild(div);
}
});
var hoverElement = document.querySelectorAll('.grid');
hoverElement.forEach(function() {
element.addEventListener('mouseover', function() {
element.style.backgroundColor = 'blue';
});
});
clearButton.addEventListener("click", function() {
input.disabled = false;
input.value = 0;
var divs = gridContainer.getElementsByClassName('grid');
while (divs.length > 0) {
gridContainer.removeChild(divs[0]);
}
});
2
Answers
if you try to make a hover affect, become blue when mouse is enter and return (not blue) when the mouse leave, it’s easier to use css.
but if you what the div after the mouse leave to stay blue it’s right to use js. however i believe you just forget to add "element" in function that used in each element inside hoverElement.
Based on your comment on a previous answer, "I should have specified I do want it to stay blue when I stop hovering…", it seems you want the grid boxes to stay blue once they’re no longer hovered.
This makes using a
CSS
only solution pretty hard (to not say impossible) so we need to do it dynamically usingJavaScript
.The idea is simple, we’ll use event delegation on the
#grid-container
instead of applying amouseover
event handler to all the grid boxes. We’ll have only onemouseover
event applied to#grid-container
element which will handle changing the background color of the grid boxes.We’ll create a new
CSS
class, let’s call it.blue
for example, that will be applied to the boxes to change their background colors to blue.The process is simple: once the
#grid-container
gets hovered we’ll see if the mouse is on a box and if yes we’ll apply our.blue
class to that box (unless it has already been applied).That might sound hard or complicated but believe me it’s not, the following code snippet should make things even clearer.