Ad

Event Listener Stops Listening

I've set up a 16x16 square grid and made the background of each square change color when hovered over.

I then have a button to clear the starting grid and prompt the user for dimensions for a new grid, which then sets up the next grid and seems to work fine.

However, at this stage, the existing Event Listener for the 'mouseover' event no longer works.

I've checked all the syntax and for any variable name clashes and have come unstuck - please help!

My script/html/css is here: https://codepen.io/Turbo124/pen/KKyMzxX

and my script is also shown below - thank you.

const gridContainer = document.querySelector('#grid-container');

function makeGrid(rows, cols) {
    gridContainer.style.setProperty('--gridRows', rows);
    gridContainer.style.setProperty('--gridCols', cols);
    for (let i = 0; i < (rows * cols); i++) {
        let newCell = document.createElement("div");
        // newCell.textContent = (i + 1);
        newCell.classList.add("cells");
        gridContainer.appendChild(newCell);
    }
   
}

makeGrid(16,16);

document.querySelectorAll('.cells').forEach(cell => {
    cell.addEventListener('mouseover', event => {
        cell.style.backgroundColor = "blue";
        console.log("hover");
    })
})

button = document.getElementById("button");
button.addEventListener("click", clearGrid);
button.addEventListener("click",setGrid);

function clearGrid() {
    let temp = gridContainer.childElementCount;
    for (let i = 0; i < temp; i++) {
    gridContainer.removeChild(gridContainer.childNodes[0]);
    }
}

function setGrid() {
    let temp = prompt("Enter number of squares per side")
    makeGrid(temp, temp);

};
Ad

Answer

Your issue is the mouse over wont work on the dynamically created elements try and place the mouseover on the parent div and check which target element triggered the event.Here have a look at this an article about event delegation https://davidwalsh.name/event-delegate.

Ad
source: stackoverflow.com
Ad