My goal is to create a 16x16 grid with a white background, where each grid item changes color when the mouse is pressed and moved over it, similar to paint. I have written a script to achieve this:
let gridContainer = document.getElementById('grid-container');
let gridArray = [];
for(let i = 0; i < 256; i++){
let div = document.createElement('div');
div.setAttribute('class', 'grid-item');
gridContainer.append(div);
gridArray[i] = div;
}
gridContainer.addEventListener("mousedown", draw)
gridContainer.addEventListener("mouseup",stopDraw)
function draw(){
gridArray.forEach(item => item.addEventListener("mouseover", () => {
(item.classList.add('hover'))
}));
}
function stopDraw(){
gridArray.forEach(item => item.removeEventListener("mouseover", () => {
(item.classList.add('hover'))
}));
}
The hover class adds a blue background color to the grid item.
Although I have tried various approaches, I still encounter the same issue where the draw function remains active even after the mouse is released. I am using vanilla JS and I am still in the process of learning the basics.
For a better understanding of my problem, here is a link to my code: https://codepen.io/ahmedmk11/pen/VwrmyGW
EDIT: Upon reflection, I realize that my initial explanation was not clear. The draw function works correctly, but it does not cease when the mouse button is released. I intend for it to only be active when the mouse button is pressed and held, like a pen.