Search code examples
javascripthtmlcsscss-grid

How can I change background color of a specific grid box?


Below is my current code and the goal is to have a single grid box change to a random specified color when the mouse hovers over it. I am trying to add an event listener to each grid item and when the mouseover occurs the color changes, but when I run this there are no color changes.

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>

    <style>
        .square {
            background-color: #737373;
            float: left;
            position: relative;
            width: 30%;
            padding-bottom: 30.66%;
            margin: 1%;
        }
    </style>
</head>
<body>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>

    <script type="text/javascript">

        var color = [, "#3C9EE7", "#E7993C",
            "#E73C99", "#3CE746", "#E7993C"];

        document.querySelectorAll(".square").forEach(item => {
            item.addEventListener("mouseover", event => {

            document.getElementById(item).style.background
                    = color[Math.floor(Math.random() * color.length)];
            }
        })

    </script>
</body>
</html>

I also tried this Javascript code with no luck:

let squares = document.querySelectorAll(".square");

for (i in squares) {
            i.addEventListener("mouseover", function() {

            document.getElementById(item).style.background
                    = color[Math.floor(Math.random() * color.length)];
            })
        }

Solution

  • Try this syntax:

    var color = [, "#3C9EE7", "#E7993C",
                "#E73C99", "#3CE746", "#E7993C"];
                                    
    let squares= document.querySelectorAll('.square');
    
    squares.forEach(item => item.addEventListener('mouseover', (e) => {
        changeColor(item);
    }))
    
    
    const changeColor = (item) => {
      item.style.background = color[Math.floor(Math.random() * color.length)];
    }
    .square {
        background-color: #737373;
        float: left;
        position: relative;
        width: 30%;
        padding-bottom: 30.66%;
        margin: 1%;
    }
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>