0

Developing an Etch-A-Sketch project using JavaScript - run into an issue which I'm not entirely sure about. Trying to attach an event to div2 however - it doesn't seem to be defined even though I have assigned const div2 = document.createElement('div') inside a for loop which creates a 16 x 16 grid:

![16 * 16 grid created using JS]1

for(let i = 0; i < 16; i++){
    const div =  document.createElement('div');
    div.style.cssText = 'border: 1px solid black; flex: 1';
    container.appendChild(div);

    for (let j = 0; j < 16; j++){
        const div2 = document.createElement('div');
        div2.classList.add('square');
        div.style.display = 'flex';
        div.appendChild(div2);    
    }
}   
div2.addEventListener('mouseover', function(){
let randomColor = colors[Math.floor(Math.random() * colors.length)];

if(randomColor === '1'){
    div2.style.changeBackground = 'red';
} else if(randomColor === '2'){
    div2.style.changeBackground = 'blue';
} else if(randomColor === '3'){
    div2.style.changeBackground = 'yellow';
} else if(randomColor === '4'){
    div2.style.changeBackground = 'orange';
} else{
    div2.style.changeBackground = 'green';
}

});

I also tried attaching the same event to square which is a class grabbed using a querySelector - however that returns null - 'Uncaught TypeError: square.addEventListener is not a function'. My overall aim is to have the user hover over a square on the grid and have the grid change colour when the cursor goes over it.

safdari
  • 25
  • 5

0 Answers0