Search code examples
javascriptgetelementsbyclassname

eventListener function to change the color of a div with class


i am trying to change the color of divs when mouse cursor hovers on them. currently i am stuck in the stage of finding a function to do so. The class elements put me in dificulty Do you have a a suggestions on what the function might look like? or maybe other methods? My JS code is bellow attached, in comments i have described what i am trying to achieve.

const 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++) {
    let cell = document.createElement('div');
    cell.innerText = (c + 1);
    container.appendChild(cell).className = 'grid-item';
  }
}

makeRows(16, 16);

let gridItem = document.querySelectorAll('grid-item');

function changeColor() {
  gridItem.style.color = "blue";
}

let pointerIn = document.getElementsByClassName('grid-item');

let i = pointerIn.length;
while (i--)
  pointerIn[i].addEventListener('mouseover', function() {
    changeColor();
  });
<div id="container"></div>


Solution

  • For simplifying you can just have an event listener for the container and then test if a "grid-item" was clicked.

    const container = document.getElementById('container');
    
    container.addEventListener('click', e => {
      if (e.target.classList.contains('grid-item')) {
        e.target.classList.toggle('selected');
      }
    });
    
    function makeRows(rows, cols) {
      container.style.setProperty('--grid-rows', rows);
      container.style.setProperty('--grid-cols', cols);
    
      let numbers = Array.from(Array(rows * cols).keys());
      numbers.forEach(num => {
        let cell = document.createElement('div');
        cell.innerText = (num + 1);
        cell.className = 'grid-item';
        container.appendChild(cell);
      });
    }
    
    makeRows(16, 16);
    .selected {
      color: blue;
      background-color: lightBlue;
    }
    <div id="container"></div>