'JAVASCRIPT: change background color of a div, when hover over it while pressing the mouse click down

I am trying to change the div background color when i hover over them clicking my mouse button.This is what i did so far. I want to make it like a drawing pen, so it won't change color when hover over but it will when hover over while pressing the mouse key.

const container = document.querySelector('.container');


function canvas(size) {
    container.style.setProperty('--grid-column', size);
    container.style.setProperty('--grid-row', size);

    for (let i = 0; i < size*size; i++) {
        const cell = document.createElement('div');
        cell.addEventListener('mouseover', changeColor);
        cell.addEventListener('mousedown', changeColor);
        container.appendChild(cell).className = 'grid-items';
    }
}
canvas(16)


function changeColor(e) {
    if (e.type == 'mouseover' && !mousedown) return
    else{
        let color1 = Math.floor(Math.random() * 256);
        let color2 = Math.floor(Math.random() * 256);
        let color3 = Math.floor(Math.random() * 256);

        e.target.style.backgroundColor = `rgb(${color1},${color2},${color3})`
    }
}

live site : https://alucard2169.github.io/Etch-a-Sketch/

repo: https://github.com/Alucard2169/Etch-a-Sketch.git



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source