I am doing a "pixel art" web page, and I don’t want the "pencil" to draw when I am not pressing the button on the mouse, I try to do this but either I can make the "pencil" work with the click or with the mouseover. In conclusion I want to click and keep dragging the mouse to draw with the click pressed down.
What is doing my code right now is working with the mouseover without pressing down. Hope you can help me
const GRIDSIDE = 600;
let side = 16;
const grid = document.querySelector(".grid");
for (let i = 0; i < (side * side); i++) {
const gridElement = document.createElement("div");
grid.appendChild(gridElement);
gridElement.classList.add("gridElement");
gridElement.style.width = ${(GRIDSIDE / side) - 2}px;
gridElement.style.height = ${(GRIDSIDE / side) - 2}px;
gridElement.addEventListener("mousedown", addColor);
gridElement.addEventListener("mouseover", addColor);
}
function addColor() {
this.style.backgroundColor = "black";
}
body {
background-color: aliceblue;
}
.grid {
width: 600px;
height: 600px;
margin: 100px auto;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
background-color: white;
box-shadow: 10px 10px #D6EAF8;
}
.gridElement {
flex: none;
border: 1px solid whitesmoke;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch-A-Sketch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="grid"></div>
<script src="script.js"></script>
</body>
</html>
3
Answers
First, your template literals don’t have the back ticks around them.
Now, there may be a more concise way to do this, but it seems to me that you need 3 events: one to initiate the highlighting, one to continue highlighting as you move the mouse, and one to cancel the highlighting.
See comments inline:
You can add event listeners for mousedown, mouseup, and mouseover to handle a drawing logic and then track the mouse state with the variable.
You can also take out of the creating div loop the eventListeners for each div and check for event.target that has .gridElement class