Aatthi Vela
Aatthi Vela

Reputation: 35

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 = '';
});``

Upvotes: 1

Views: 109

Answers (2)

Jy T
Jy T

Reputation: 86

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);

Upvotes: 1

Dylan Bozarth
Dylan Bozarth

Reputation: 1704

Forgive me if this seems like a dumb suggestion, but why not use the css:hover property for this?

.grid-item:hover {
  background-color: black;
}

https://www.w3schools.com/cssref/sel_hover.asp

Upvotes: 0

Related Questions