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/
I found this to work the best
const container = document.querySelector('.container');
const button = document.createElement('button');
let size;
button.classList.add('clear');
button.innerText = 'CLEAR';
document.body.appendChild(button);
var mouseDown = false;
document.body.onmousedown = function() {
mouseDown = true;
};
document.body.onmouseup = function() {
mouseDown = false;
};
button.addEventListener('click', function() {
container.innerHTML = '';
size = prompt('what size do you want your grid to be: ');
checkSize(size);
});
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 (mouseDown) {
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})`;
}
}
function checkSize(e) {
if (e > 100) {
alert("size can't be greater than 100");
canvas(16);
} else {
canvas(e);
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: black;
display: flex;
height: 100vh;
align-items: center;
justify-content: center;
}
.container {
display: grid;
width: 25rem;
height: 30rem;
background: white;
grid-template-columns: repeat(var(--grid-column), 1fr);
grid-template-rows: repeat(var(--grid-row), 1fr)
}
.grid-items {}
.clear {
padding: 1rem 2rem;
border: none;
border-radius: 10px;
margin: 5rem 0 0 5rem;
}
<div class="container"></div>
In this if the user is pressing the mouse down over the canvas, the color changes as the mouse moves.