skip to Main Content

How do I access the divs and color them when the mouse is hovered over them. They are created inside a bigger container when the user inputs a value and i cannot access them by another fucntion.

HTML

<body>
    <div>   
        <div id="outer_container">
        <div id="container"> </div>
    </div>
    
    <div id="user_input_container">
        <input type="color" class="user_input" name="" id="colour_picker" value="#000000">

        <button class="user_input" id="rainbow">Rainbow</button>
    <div>

        <div>
            <input class="user_input" type="range" min="2" max="100" value="16" name="options"
                id="grid_range">
        </div>

</body>

Javascript

let container = document.getElementById(`container`);
function createGrid(number) {
  totalNumber = number * number;
  while (container.hasChildNodes()) {
    container.removeChild(container.firstChild);
  }

  for (let i = 0; i < totalNumber; i++) {
    let gridSquare = document.createElement("div");
    gridSquare.classList.add("grid_square");

    let cellwidth = container.clientWidth / number + `px`;
    let cellheight = container.clientHeight / number + `px`;

    gridSquare.style.width = `${cellwidth}`;
    gridSquare.style.height = `${cellheight}`;
    container.appendChild(gridSquare);
  }
}

document.addEventListener("DOMContentLoaded", () => {
  createGrid(range.value);
});

let range = document.getElementById(`grid_range`);

range.addEventListener(`change`, () => {
  createGrid(range.value);
});

let color = document.getElementById(`colour_picker`);

What I did was just add an eventlistener() in the createdGrid() function that takes the value from "color" picker, but really not able to access the divs inside and get them colored by and oustside fucntions specifically for coloring.

The eventlistener() below is what I added inside the for() loop of createdGrid function.

 gridSquare.addEventListener("mouseover", (event) => {
      event.target.style.backgroundColor = color.value;
    });

Thanks!

2

Answers


  1. To do what you require, add a mouseenter and mouseleave event handler to the gridSquare elements you create within each loop. One event adds the background-color and the other removes it.

    let container = document.querySelector('#container');
    let color = document.querySelector('#colour_picker')
    
    document.addEventListener("DOMContentLoaded", () => {
      createGrid(range.value);
    });
    
    function createGrid(number) {
      totalNumber = number * number;
      while (container.hasChildNodes()) {
        container.removeChild(container.firstChild);
      }
    
      for (let i = 0; i < totalNumber; i++) {
        let gridSquare = document.createElement("div");
        gridSquare.classList.add("grid_square");
    
        let cellwidth = container.clientWidth / number + `px`;
        let cellheight = container.clientHeight / number + `px`;
    
        gridSquare.style.width = cellwidth;
        gridSquare.style.height = cellheight;
        
        gridSquare.addEventListener('mouseenter', e => e.target.style.backgroundColor = color.value);
        gridSquare.addEventListener('mouseleave', e => e.target.style.backgroundColor = 'transparent');
        container.appendChild(gridSquare);
      }
    }
    
    let range = document.getElementById(`grid_range`);
    range.addEventListener(`change`, () => {
      createGrid(range.value);
    });
    #container {
      height: 300px;
      width: 300px;
    }
    
    .grid_square {
      border: 1px solid #CCC;
      display: inline-block;
    }
    
    #user_input_container {
      position: fixed;
      right: 10px;
      top: 10px;
    }
    <div>
      <div id="outer_container">
        <div id="container"></div>
      </div>
      <div id="user_input_container">
        <input type="color" class="user_input" name="" id="colour_picker" value="#000000">
        <button class="user_input" id="rainbow">Rainbow</button>
        <div>
          <div>
            <input class="user_input" type="range" min="2" max="100" value="16" name="options" id="grid_range">
          </div>
        </div>
      </div>
    </div>
    Login or Signup to reply.
  2. To achieve the functionality of changing the color of the divs when the mouse is hovered over them based on the color selected by the user, you can create a separate function for coloring the divs.

    let container = document.getElementById(`container`);
    let colorPicker = document.getElementById(`colour_picker`);
    let range = document.getElementById(`grid_range`);
    
    function createGrid(number) {
        totalNumber = number * number;
        while (container.hasChildNodes()) {
            container.removeChild(container.firstChild);
        }
    
        for (let i = 0; i < totalNumber; i++) {
           let gridSquare = document.createElement("div");
           gridSquare.classList.add("grid_square");
    
           let cellwidth = container.clientWidth / number + `px`;
           let cellheight = container.clientHeight / number + `px`;
    
           gridSquare.style.width = `${cellwidth}`;
           gridSquare.style.height = `${cellheight}`;
           container.appendChild(gridSquare);
    
           // Add event listener for coloring on mouseover
           gridSquare.addEventListener("mouseover", handleGridSquareMouseOver);
       }
    }
    
    function handleGridSquareMouseOver(event) {
        event.target.style.backgroundColor = colorPicker.value;
    }
    
    document.addEventListener("DOMContentLoaded", () => {
        createGrid(range.value);
    });
    
    range.addEventListener(`change`, () => {
         createGrid(range.value);
    });
    
     // You can also add an event listener for the color picker change if needed
     colorPicker.addEventListener('input', () => {
       // Update the existing grid with the new color
       updateGridColor(colorPicker.value);
    });
    
    function updateGridColor(color) {
       let gridSquares = document.getElementsByClassName("grid_square");
       for (let i = 0; i < gridSquares.length; i++) {
          gridSquares[i].style.backgroundColor = color;
       }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search