Home > Software engineering >  Make the background-color of div change when the mouse is down and hovering
Make the background-color of div change when the mouse is down and hovering

Time:01-17

When hovering over a div along with the mouse being constantly held down, I would like the background-color of the div to be changed.

Code:

<style>
    #container{
        margin: auto;
        margin-top: 20px;
        height: 200px;
        width: 200px;
        background-color: aquamarine;

        display: grid;
        grid-template-columns: repeat(4, 1fr);
        grid-template-rows: repeat(4, 1fr);
    }
</style>
<body>
    <div id="container">
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
        <div ></div>
    </div>

    <script>
        let cells=Array.from(document.getElementsByClassName('cell'));
        cells.forEach(cell => {
            cell.onmouseover = () => {
                cell.onmousedown = () => {
                    cell.style.backgroundColor="black";
                }
            }
        });
    </script>

The problem is that the div only turns black on the first click. There is no change on the other div's when the mouse is then subsequently dragged over them while the mouse is constantly being held down. The cursor just turns into a red circle-backslash symbol.

I have tried adding an event (as seen in the code above) where if the element is moved over but only when the mouse is down, it transforms the background-color to black.

Oh, and I'd like to only use vanilla js, not jQuery or any additional extensions.

CodePudding user response:

try with the following script. It works on my side

<script>
            let cells=Array.from(document.getElementsByClassName('cell'));

            let flag = false;
            
            window.onmouseup = () => {                        
                flag = false;
            }
            cells.forEach(cell => {
                cell.onmouseover = () => {
                    if(flag == true)
                    {
                        cell.style.backgroundColor="black";
                    }
                    cell.onmousedown = () => {
                        cell.style.backgroundColor="black";
                        flag = true;
                    }                  

                    
                }
            });
        </script>
  • Related