1
votes

New to JS. Im trying to get my color button and other buttons working, where on clicking the color button, the grid blocks will be colored in black after mouseover. I'm trying to add eventlisteners in the play function to change the backgroundcolor of gridSquare, but can't because of the scope. How would i go about doing this?

JS

const colorBtn = document.getElementById('color')
const eraseBtn = document.getElementById('erase')
const clearBtn = document.getElementById('clear')
const gridCont = document.getElementById('grid')
let currentMode = ''
// creates grid on pageload
function makeGrid() {
    for (i=0; i<1600; i++) {
        let gridSquare = document.createElement('div')
        gridCont.appendChild(gridSquare)
        gridSquare.classList.add('gridSquare')
    }
}


window.onload = makeGrid()
//

colorBtn.addEventListener('click', () => {
    currentMode = 'color'
    
})

eraseBtn.addEventListener('click', () => {
    currentMode = 'erase'
})

clearBtn.addEventListener('click', () => {
    currentMode === 'clear'
})

function play() {
   if (currentMode === 'color') {
       
   }
}

window.onload = play()

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>scribblyscrabblydoo</title>
    <link rel="stylesheet" href="./styles.css">
</head>
<body>
    <div class="titlebox">
        <h1>sribblyscrabblydoo</h1>
        <p>Draw or something idk bro</p>
    </div>
    <div class="mainbod">
        <div class="options">
            <div class="buttons">
                <h2>Options</h2>
            </div>
            <div class="buttons">
                <button id="color">Color</button>
            </div>
            <div class="buttons">
                <button id="erase">Erase</button></div>
            <div class="buttons">
                <button id="clear">Clear</button>
            </div>
            <div class="buttons">
                <button id="github">Duskope Github</button>
            </div>
        </div>
        <div id="grid"></div>
    </div>
</body>
<script type="text/javascript" src = "index.js"></script>
</html>

https://duskope.github.io/scribblyscrabblydoo/


1

1 Answers

0
votes

To solve the background color issue, its actually just a typo. Change your play function to this

Fyi, you're gonna run into another issue of it making EVERYTHING black. So add some conditionals.

function play() {
   document.querySelectorAll('.gridSquare').forEach((item) => {
       addEventListener('mouseover', (e) => {
           e.target.style.backgroundColor = 'black'
       })
   })
}