I'm trying to make it so that hovering over any of the squares inside the play area adds the class "darken" to them. The play area generates as expected, but instead of adding the class, any time I hover over the squares in question I get "Uncaught TypeError: cannot read properties of undefined (reading 'add') at HTMLDivElement.".
I've tried both the line with the event listener in the "createPlayArea" function and the commented out variable + function combo below and I end up with the exact same error in my chrome console.
const squareAmount = 50;
const dimensions = '10px';
function createPlayArea() {
for (i = 0; i < (squareAmount * squareAmount); i++) {
let squares = document.createElement('div')
squares.setAttribute('style', 'display: flex; flex-wrap: wrap;')
squares.classList.add('square')
squares.style.height = dimensions;
squares.style.width = dimensions;
squares.addEventListener('mouseover', square => square.classList.add('darken'))
playArea.appendChild(squares)
}
}
createPlayArea()
// let playSquares = document.querySelectorAll('.square')
// function pen() {
// playSquares.forEach(square => square.addEventListener('mouseover', function (e) {
// e.classList.add('darken')
// }))
// }
// pen()
<style>
.square {
background-color: gray;
}
.darken {
background-color: black;
}
</style>
<div id="playArea">
</div>
What I was expecting is for the .darken class to be added to the squares that get hovered over. All I got was this stupid error :')