I'm currently doing the etch-a-sketch project of The Odin Project curriculum.
I have this event that when i click and mouseover the div, changue the background color, but I don't know how to remove this event when i release the click.
I tried using removeEventListener, tried using mouseup event but I can't figure out how to make this work.
I want to click and mouseover to draw and when i release the click stop the mouseover and stop to draw.
Another thing is that when I click in some div, this div do not change the background color immediately unless I move to another one on his side, then this other change the color.
Here is my code.
The HTML <body> only have a <div> with "grid-container" Id
JavaScript:
const divCont = document.getElementById("grid-container");
for (i = 1; i<=16; i++) {
let divCol = document.createElement('div')
divCol.classList.add("grid");
for ( j = 1; j<=16; j++){
let divRow = document.createElement('div');
divRow.classList.add("secGrid");
divCol.appendChild(divRow);
}
divCont.appendChild(divCol);
}
const hoverDivs = [...document.querySelectorAll('.secGrid')];
function colorChange(){
hoverDivs.forEach(hoverDiv => {
hoverDiv.addEventListener('click', () => {
hoverDivs.forEach(hoverDiv => {
hoverDiv.addEventListener('mouseover', () => {
hoverDiv.style.backgroundColor = "black"
});
});
});
});
}
colorChange();
CSS:
* body {
box-sizing: border-box;
padding: 0;
margin: 0;
}
#container {
max-width: fit-content;
margin: auto;
}
#grid-container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width:100vh;
max-width:100%;
height:100vh;
max-height:100%;
position:relative;
background:red;
background-color: black;
}
.grid {
display: flex;
flex-direction: column;
flex-wrap: wrap;
flex-basis: 100%;
background-color: blue;
}
.secGrid {
background-color: yellow;
flex-basis: 100%;
}
I already have a solution.
I set a variable that says if it's onmousedown
or not (changeColor
). So if changeColor
is true, onmouseover
is active, if not, isn't active.
const divCont = document.getElementById("grid-container");
for (i = 1; i<=16; i++) {
let divCol = document.createElement('div')
divCol.classList.add("grid");
for ( j = 1; j<=16; j++){
let divRow = document.createElement('div');
divRow.classList.add("secGrid");
divCol.appendChild(divRow);
}
divCont.appendChild(divCol);
}
const hoverDivs = [...document.querySelectorAll('.secGrid')];
let changeColor = false;
hoverDivs.forEach(hoverDiv => {
hoverDiv.addEventListener('mousedown', () => {
hoverDiv.style.backgroundColor = "black"
changeColor=true;
});
hoverDiv.addEventListener('mouseup', () => {
changeColor=false;
});
hoverDiv.addEventListener('mouseover', () => {
if(changeColor){
hoverDiv.style.backgroundColor = "black";
}
});
});