skip to Main Content

I am trying to create a mouseover event that turns divs blue when I hover over them. I am looping over each div with forEach and expect it to turn blue when hovered over. However, the code is not working at all. I have determined that the nodelist has a length of 0, but I am not sure why that is. I want it to stay blue even after I stop hovering over it, which is why I am using js.

var form = document.getElementById("inputForm");
var clearButton = document.getElementById("clear");
var input = form.querySelector("input");

//Starts function that does everything

form.addEventListener("submit", function(e) {

//Prevents browser from refreshing on submit

    e.preventDefault();

input.disabled = true;
var boxInput = input.value;
var gridContainer = document.getElementById("gridContainer");
console.log(boxInput);

for (var i = 0; i <= boxInput * boxInput - 1; i++) {

//Creates a certain number of rows and columns based on user input

    gridContainer.style.gridTemplateColumns =  `repeat(${boxInput}, 1fr)`;
    gridContainer.style.gridTemplateRows =  `repeat(${boxInput}, 1fr)`;
    var div = document.createElement("div");
    console.log(div);
    div.className = "grid";
    gridContainer.appendChild(div);
}
});

var hoverElement = document.querySelectorAll('.grid');

hoverElement.forEach(function() {
    element.addEventListener('mouseover', function() {
      element.style.backgroundColor = 'blue';
    });
  });

clearButton.addEventListener("click", function() {
   input.disabled = false;
   input.value = 0;
   var divs = gridContainer.getElementsByClassName('grid');
   while (divs.length > 0) {
    gridContainer.removeChild(divs[0]);
   }
});

2

Answers


  1. if you try to make a hover affect, become blue when mouse is enter and return (not blue) when the mouse leave, it’s easier to use css.

    .grid:hover {
        background-color: blue;
    }
    

    but if you what the div after the mouse leave to stay blue it’s right to use js. however i believe you just forget to add "element" in function that used in each element inside hoverElement.

    hoverElement.forEach(function (element) {
        element.addEventListener('mouseover', function () {
            element.style.backgroundColor = 'blue';
        });
    });
    
    Login or Signup to reply.
  2. Based on your comment on a previous answer, "I should have specified I do want it to stay blue when I stop hovering…", it seems you want the grid boxes to stay blue once they’re no longer hovered.

    This makes using a CSS only solution pretty hard (to not say impossible) so we need to do it dynamically using JavaScript.

    The idea is simple, we’ll use event delegation on the #grid-container instead of applying a mouseover event handler to all the grid boxes. We’ll have only one mouseover event applied to #grid-container element which will handle changing the background color of the grid boxes.

    We’ll create a new CSS class, let’s call it .blue for example, that will be applied to the boxes to change their background colors to blue.

    The process is simple: once the #grid-container gets hovered we’ll see if the mouse is on a box and if yes we’ll apply our .blue class to that box (unless it has already been applied).

    That might sound hard or complicated but believe me it’s not, the following code snippet should make things even clearer.

    /**
     * The solution will work with elements already found in the DOM as well as dynamically created elements.
     * The solution illustrates both cases.
     */
    
    
    /*
     * Select the "#grid-element" so we can apply our event handler (mouseover) 
     * The dynamicBoxes is not really necessary, it only holds dynamically created elemnt to showcase that the solution works on dynamically created elements
     */
    const gridContainer = document.getElementById('grid-container'),
      dynamicBoxes = [];
    
    // loop counter
    let i = 4;
    
    // just create some box elements...
    for (; i++ < 8;) {
      const box = document.createElement('div');
      box.textContent = `Am a grid element dynamically created (No: ${i})`;
      box.classList.add('box');
      dynamicBoxes.push(box);
    }
    
    // append those boxes to "#grid-container"
    gridContainer.append(...dynamicBoxes);
    
    // the mouseover event listener
    gridContainer.addEventListener('mouseover', e => {
      // "e.target" holds the element being hovered, i.e the one that the mouse is over.
      const cls = e.target.classList;
    
      /* halt the function execution if:
      *     - the hovered element is not a box (it doesn't have the ".box" class
            - OR that box already has the ".blue" class
      */
      if (!cls.contains('box') || cls.contains('blue')) return;
    
      // apply the ".blue" class to the hovered box
      cls.add('blue');
    });
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    #grid-container {
      padding-inline: 15px;
    }
    
    .box {
      margin: 15px 0;
      padding: 15px;
      border-radius: 8px;
      border: 2px solid #c3c3c3;
    }
    
    .box.blue {
      background-color: #00f;
      color: #fff;
    }
    <div id="grid-container">
      <div class="box">Am a grid element already in the DOM (No: 1)</div>
      <div class="box">Am a grid element already in the DOM (No: 2)</div>
      <div class="box">Am a grid element already in the DOM (No: 3)</div>
      <div class="box">Am a grid element already in the DOM (No: 4)</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search