javascripteventsmouseeventmouseovermouseleave

Eventlistener for 'mouseover' and 'mouseleave'


I am trying to make each cell change colour when the mouse hovers above them and return it to the default colour when the mouse leaves. I only created the .container div with HTML while the other divs were created with JS loops so I'm finding it difficult to execute the code.

I am pretty sure I need to make the cells a variable outside the function but if that's the case I'm not sure how to do it. Can someone help?

``let container = document.getElementById("container");


function makeRows(rows, cols) {
  container.style.setProperty('--grid-rows', rows);
  container.style.setProperty('--grid-cols', cols);
  for (c = 0; c < (rows * cols); c++) {
    const cell = document.createElement("div");
    cell.innerText = (c + 1);
    container.appendChild(cell).className = "grid-item";
  };
};

makeRows(16, 16);

var gridCells = document.querySelectorAll(".grid-item"); 

gridCells.addEventListener('mouseover', () => {
  gridCells.style.backgroundColor = 'black';
});

gridCells.addEventListener('mouseleave', () => {
  gridCells.style.backgroundColor = '';
});``

Solution

  • You could put the event listener in the loop if you can only use javascript. Or you could just use css .grid-item:hover {background-color: black;}

    let container = document.getElementById("container");
    
    
    function makeRows(rows, cols) {
      container.style.setProperty('--grid-rows', rows);
      container.style.setProperty('--grid-cols', cols);
      for (c = 0; c < (rows * cols); c++) {
        const cell = document.createElement("div");
        cell.innerText = (c + 1);
        container.appendChild(cell).className = "grid-item";
        cell.addEventListener('mouseover', () => {
          cell.style.backgroundColor = 'black';
        });
        cell.addEventListener('mouseleave', () => {
           cell.style.backgroundColor = 'white';
        });
      }
    };
    
    makeRows(16, 16);