Continuous call on EventListener on mousedown - javascript

I'm working on an Etch A Sketch app for The Odin Project and I want to adjust one of the requirements where all I need to do is move the mouse on screen as a continuous stroke where each pixel touched on mouseover is filled, which is what's happening right now with my code.
What I want to change is the mouseover on my tile EventListener where it's really a continuous stroke on mousedown. I did try changing the e.target command in the setTiles function to toggle after changing the tile.addEventListener to mousedown, but it only works on each press of the left mouse button.
I'm trying to figure out a way to make this continuous on mousedown instead of using mouseover. I've included the code I have so far in the question.
const container = document.querySelector('#container');
const grid = document.querySelector('#grid');
const userInput = document.querySelector('#user-input');
let penDown = false;
grid.style.fontSize = '1em';
// Set pixel width and height
let wdt = '1em';
let hgt = '1em';
// Ask the user for the number of tiles for the sketch grid
function getUserInput() {
let input = parseInt(prompt(`Please enter the grid size you'd like`));
input <= 100 || !isNaN(input)
? createSketchGrid(input)
: alert('Please enter a valid number less than or equal to 100.');
}
// Event listener to create tiles in mouseover
function setTiles(e) {
e.target.classList.add('fill');
}
// function deleteTiles(e) {
// e.target.classList.toggle('fill');
// }
container.addEventListener('mousedown', function () {
penDown = true;
});
container.addEventListener('mouseup', function () {
penDown = false;
});
// Create the grid
function createSketchGrid(tiles) {
let gridSize = tiles * tiles;
for (let i = 0; i < gridSize; i++) {
let tile = document.createElement('div');
tile.style.width = wdt;
tile.style.height = hgt;
grid.appendChild(tile);
// tile.addEventListener('mouseover', setTiles, false);
if ((penDown === true)) {
tile.addEventListener('mousemove', setTiles);
}
}
}
userInput.addEventListener('click', getUserInput);
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-size: 10px;
}
h1 {
font-size: 3rem;
}
.grid {
/* font-size: 1.6rem; */
display: flex;
flex-wrap: wrap;
gap: 0.1em;
border: 2px solid black;
background-color: lightgrey;
flex: 0 0 32em;
}
.fill {
flex-wrap: wrap;
background-color: black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch A Sketch</title>
<link rel="stylesheet" type="text/css" href="styles/style.css">
<script type="text/javascript" src="js/main.js" defer></script>
</head>
<body>
<h1 class="title">Etch A Sketch</h1>
<div id="container" class="container">
<button id="user-input" class="btn user-input" value="Grid Size">Grid Size</button>
<div id="grid" class="grid">
</div>
</div>
</body>
</html>

Related

Is there a way to make the cells of a grid fill in the space when the grid's size changes?

I'm making a grid and I'm not sure how to make the cells fill the space between them when the grid size changes.
I have a function that generates a grid and receives size as a parameter.
What should be added to the grid-square class to make the cells fill the entire space?
//get the grid div
const container = document.querySelector("#container");
function changeColor(e) {
const hoverColor = Math.floor(Math.random() * 16777215).toString(16);
e.target.style.backgroundColor = "#" + hoverColor;
}
function createDivs(size) {
//generate grid elements
for (let i = 0; i < size * size; i++) {
const newDiv = document.createElement("div");
newDiv.classList.add("grid-square");
newDiv.addEventListener("mouseover", changeColor);
container.appendChild(newDiv);
}
}
createDivs(2);
* {
box-sizing: border-box;
}
#container {
display: flex;
background-color: rgba(49, 49, 49, 0.281);
width: 50vw;
height: 50vh;
flex-wrap: wrap;
}
.grid-square {
background-color: white;
width: 50%;
aspect-ratio: 1/1;
}
.grid-square:hover {
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Etch a Sketck</title>
<link rel="stylesheet" href="style.css" />
<script src="script.js" defer></script>
</head>
<body>
<div id="container"></div>
</body>
</html>
So this is the way I did it. I changed from flex box to grid. Grid has a property called grid-template-columns that defines how many columns you have and how wide each one is. The syntax here is grid-template-columns: repeat(n, 1fr) where n is the number of columns you want.
In order to set the column numbers in javascript, I've used a css custom property (also called a css variable) to define the column numbers. To set the custom property itself I've set the element's style attribute to define that property on load.
Have a look below:
//get the grid div
const container = document.querySelector("#container");
function changeColor(e) {
const hoverColor = Math.floor(Math.random() * 16777215).toString(16);
e.target.style.backgroundColor = "#" + hoverColor;
}
function createDivs(size) {
//generate grid elements
for (let i = 0; i < size * size; i++) {
const newDiv = document.createElement("div");
newDiv.classList.add("grid-square");
newDiv.addEventListener("mouseover", changeColor);
container.appendChild(newDiv);
}
// Added this
container.style.cssText="--cols: "+size;
}
createDivs(5);
* {
box-sizing: border-box;
}
#container {
/* added this */
display: grid;
grid-template-columns: repeat(var(--cols), 1fr);
/* end of added css */
background-color: rgba(49, 49, 49, 0.281);
width: 50vw;
height: 50vh;
flex-wrap: wrap;
}
.grid-square {
background-color: white;
aspect-ratio: 1/1;
}
.grid-square:hover {
cursor: pointer;
}
<div id="container"></div>
The solution was to set the width when creating the cells.
//get the grid div
const container = document.querySelector("#container");
function changeColor(e) {
const hoverColor = Math.floor(Math.random() * 16777215).toString(16);
e.target.style.backgroundColor = "#" + hoverColor;
}
function createDivs(size) {
//generate grid elements
for (let i = 0; i < size * size; i++) {
const newDiv = document.createElement("div");
newDiv.classList.add("grid-square");
newDiv.addEventListener("mouseover", changeColor);
//Setting the width
newDiv.style.width = 100 / size + "%";
container.appendChild(newDiv);
}
}
createDivs(6);
* {
box-sizing: border-box;
}
#container {
display: flex;
background-color: rgba(49, 49, 49, 0.281);
width: 50vw;
height: 50vh;
flex-wrap: wrap;
}
.grid-square {
background-color: white;
width: 50%;
aspect-ratio: 1/1;
}
.grid-square:hover {
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Etch a Sketck</title>
<link rel="stylesheet" href="style.css" />
<script src="script.js" defer></script>
</head>
<body>
<div id="container"></div>
</body>
</html>

Set container size width and height with one function argument

I have a container grid, that I'm trying to set the width and height of proportionally by passing that one number as an argument tiles in my createSketchGrid function. I'm using the variable gridSize to take the arguments tiles and multiply it by itself. The result is a container that is quite a bit wider than its height.
I'm not quite sure how to set this evenly and multiplying it doesn't make it proportional, either. Is there a way to set the width and height to be the same if I use this one argument? I also think that setting the container's display property to flex may be part of the problem as well.
const grid = document.querySelector('#grid');
const userInput = document.querySelector('#user-input');
grid.style.fontSize = '1em';
// Set pixel width and height
let wdt = '1.25em';
let hgt = '1.25em';
// Ask the user for the number of tiles for the sketch grid
function getUserInput() {
let input = parseInt(prompt(`Please enter the grid size you'd like`));
input <= 100 || !isNaN(input)
? createSketchGrid(input)
: alert('Please enter a valid number less than or equal to 100.');
}
// Event listener to create tiles in mouseover
function setTiles(e) {
e.target.classList.add('fill');
}
function deleteTiles(e) {
e.target.classList.toggle('fill');
}
// Create the grid
function createSketchGrid(tiles) {
let gridSize = tiles * tiles;
for (let i = 0; i < gridSize; i++) {
let tile = document.createElement('div');
tile.style.width = wdt;
tile.style.height = hgt;
grid.appendChild(tile);
tile.addEventListener('mouseover', setTiles);
}
}
userInput.addEventListener('click', getUserInput);
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-size: 10px;
}
h1 {
font-size: 3rem;
}
.grid {
display: flex;
flex-wrap: wrap;
gap: 0.1em;
background-color: lightgrey;
flex: 0 0 32em;
}
.fill {
flex-wrap: wrap;
background-color: black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch A Sketch</title>
<link rel="stylesheet" type="text/css" href="styles/style.css">
<script type="text/javascript" src="js/main.js" defer></script>
</head>
<body>
<h1 class="title">Etch A Sketch</h1>
<div id="container" class="container">
<button id="user-input" class="btn user-input" value="Grid Size">Grid Size</button>
<div id="grid" class="grid">
</div>
</div>
</body>
</html>
Using CSS grid, we can define how many columns we want (here I have just used the regular repeat(..., ...) method), and we can also change the width of the grid to match.
const grid = document.querySelector('#grid');
const userInput = document.querySelector('#user-input');
grid.style.fontSize = '1em';
// Set pixel width and height
let wdt = '1.25em';
let hgt = '1.25em';
// Ask the user for the number of tiles for the sketch grid
function getUserInput() {
let input = parseInt(prompt(`Please enter the grid size you'd like`));
input <= 100 || !isNaN(input)
? createSketchGrid(input)
: alert('Please enter a valid number less than or equal to 100.');
}
// Event listener to create tiles in mouseover
function setTiles(e) {
e.target.classList.add('fill');
}
function deleteTiles(e) {
e.target.classList.toggle('fill');
}
// Create the grid
function createSketchGrid(tiles) {
let gridSize = tiles * tiles;
for (let i = 0; i < gridSize; i++) {
let tile = document.createElement('div');
tile.style.width = wdt;
tile.style.height = hgt;
grid.appendChild(tile);
tile.addEventListener('mouseover', setTiles);
}
// change style
grid.style.gridTemplateColumns = `repeat(${tiles}, 1fr)`;
// calculate new width
grid.style.width = `calc(${wdt} * ${tiles} + 0.1em * ${tiles - 1})`;
}
userInput.addEventListener('click', getUserInput);
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-size: 10px;
}
h1 {
font-size: 3rem;
}
.grid {
display: grid;
grid-template-columns: repeat(0, 1em);
gap: 0.1em;
background-color: lightgrey;
}
.fill {
flex-wrap: wrap;
background-color: black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch A Sketch</title>
<link rel="stylesheet" type="text/css" href="styles/style.css">
<script type="text/javascript" src="js/main.js" defer></script>
</head>
<body>
<h1 class="title">Etch A Sketch</h1>
<div id="container" class="container">
<button id="user-input" class="btn user-input" value="Grid Size">Grid Size</button>
<div id="grid" class="grid">
</div>
</div>
</body>
</html>

why grid cells wont go below 32px width and height?

im trying to make static grid with a button that can change number of boxes in it (from 16x16 to 64x64 and anything between). Grid is 40rem x 40rem, when i try to change manually number of boxes in makeGrid() function it works fine up to 20 (boxes change size accordingly), but anything above 20 stays the same size and gets cutoff from my grid. If there is no grid css overflow property stated, grid width change depending on number of boxes but boxes themself won't shrink
my code:
size button is not working yet, grid size need to be changed mannualy in makeGrid function
const grid = document.getElementById('grid');
const size = document.getElementById('size');
const eraser = document.getElementById('eraser');
const color = document.getElementById('color');
const gridBorder = document.getElementById('grid-borders');
const clear = document.getElementById('clear');
// grid
function makeGrid(number) {
number = number || 16;
let cellWidth = 40 / number + 'rem';
let cellHeight = 40 / number + 'rem';
grid.style.gridTemplateColumns = `repeat( ${number}, 1fr)`;
grid.style.gridTemplateRows = `repeat(${number}, 1fr)`;
for (let i = 0; i < number * number; i++) {
let cell = document.createElement('div');
grid.appendChild(cell).id = 'box';
cell.classList.add('border');
cell.classList.add('box');
cell.style.backgroundColor = 'white';
cell.style.width = cellWidth;
cell.style.height = cellHeight;
}
size.textContent = `${number} x ${number}`;
}
makeGrid();
// drawing on hover
color.addEventListener('click', function () {
grid.addEventListener('mouseover', function (e) {
e.target !== grid ? (e.target.style.backgroundColor = 'black') : null;
});
});
function changeColor(event) {
event.target.style.backgroundColor = 'black';
}
// erase functionality
eraser.addEventListener('click', function () {
grid.addEventListener('mouseover', function (e) {
e.target !== grid ? (e.target.style.backgroundColor = 'white') : null;
});
});
// grid borders
const allBoxes = document.querySelectorAll('.box');
gridBorder.addEventListener('click', function () {
allBoxes.forEach((box) => {
box.classList.toggle('no-border');
box.classList.toggle('border');
});
});
// clear button
clear.addEventListener('click', function () {
allBoxes.forEach((box) => {
box.style.backgroundColor = 'white';
});
});
// size button
// size.addEventListener('click', function () {
// let number = prompt(`Enter grid size less or equal to 100`);
// if (number !== Number.isInteger()) {
// return;
// } else if (number > 100) {
// number = prompt(`Enter grid size greater or equal to 100`);
// }
// });
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
background-color: aquamarine;
}
#grid {
display: grid;
justify-content: center;
border: 1px solid #ccc;
width: 40rem;
height: 40rem;
min-width: 0;
min-height: 0;
overflow: hidden;
}
.box {
padding: 1em;
}
#title {
display: flex;
align-items: flex-end;
justify-content: center;
height: 180px;
}
#container {
display: flex;
height: 60%;
width: 1259px;
align-items: flex-start;
justify-content: flex-end;
gap: 20px;
padding-top: 20px;
}
#menu {
display: flex;
flex-direction: column;
gap: 10px;
}
.border {
outline: 1px solid black;
}
.no-border {
outline: none;
}
.black-bg {
background: black;
}
.white-bg {
background: white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Etch-a-Sketch</title>
<link rel="stylesheet" href="style.css" />
<script src="script.js" defer></script>
</head>
<body>
<div id="title">
<h1>Etch-a-Sketch</h1>
</div>
<main id="container">
<div id="menu">
<button id="size"></button>
<button id="color">Color</button>
<button id="eraser">Eraser</button>
<button id="clear">Clear</button>
<button id="grid-borders">Grid Borders</button>
</div>
<div id="grid"></div>
</main>
</body>
</html>
"Why won't my grid cells go below 32px?" - have you checked your padding (hint: 32px is exactly equal to 2 * 16px which in turn is exactly equal to your padding of 1em with most browsers implementing a default font-size of 16px). –
David Thomas
box padding was set to 1em which caused my problem, after deleting it my grid worked as intended

How to make the button to clear up the sketch?

I'm doing a project to make an etch-a-sketch every time I hover on the grid. What I'm trying to do is to make a button to clear up all the colors made.
The sketch picture.
I guess what I need to do is to remove the style elements while clicking the button. But I'm just note sure how to link the button with the style elements.
const container = document.querySelector(".container");
// const table = document.createElement('div');
// table.classList.add('grid-square');
// table.textContent = 'hello';
// container.appendChild(table);
function makeTable(rows, cols) {
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', cols);
for (i = 0; i < (rows * cols); i++){
const cell = document.createElement('div');
// cell.innerText = (i + 1);
container.appendChild(cell).className = "table";
};
};
makeTable(16, 16);
// const container = document.querySelector('.container')
const grids = document.querySelectorAll('.table')
grids.forEach(element => {
element.addEventListener('mouseover', (e) => {
e.target.style.backgroundColor = randomColor();
console.log(e)
})
});
function randomColor() {
var generateColor = '#' + Math.floor(Math.random()*16777215).toString(16);
return generateColor;
}
function resizeGrid() {
sketchSize = prompt("Enter 1 to 100 to resize sketch");
return sketchSize;
}
// const button = document.querySelector('button')
// button.addEventListener('click', (e) => {
// });
:root {
--grid-rows: 1;
--grid-cols: 1;
}
.container {
display: grid;
/* grid-gap: 1em; */
grid-template-rows: repeat(var(--grid-rows), 1fr);
grid-template-columns: repeat(var(--grid-cols), 1fr);
/* border: 1px solid black; */
width: 50%;
size: 960px;
}
.table {
padding: 1em;
border: 1px solid coral;
text-align: center;
/* border: none; */
}
header {
display: flex;
justify-content: center;
margin: 20px;
gap: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch-A-Sketch</title>
<script src="index.js" defer></script>
<link rel="stylesheet" href="index.css">
</head>
<body>
<header>
<button class="clear-button">Clear</button>
<button class="resize">Resize</button>
</header>
<div class="container"></div>
</body>
</html>
Cheers!!
To answer my own question, I figured how to do it.
const clear = document.querySelector('.clear-button')
clear.addEventListener('click', () => {
grids.forEach(element => {
element.style.backgroundColor = null;
})
})
I was struggling earlier because I'm not sure how to put other elements (e.g. grids) to the new eventListener.

Why is my mousedown event triggered on a mouseup event?

I've been working on the etch-a-sketch project of the Odin project, and I came across some weird behavior when implementing the mousedown and mouseup event listeners.
I've created a 50x50 grid of divs in a container div. The container div listens on mousedown events, upon which it calls the startDrawing function, filling the boxes that the user hovers over. It also listens on mousedown events, so that when the mouse is released, the stopDrawing function is called and the filling of boxes stops.
All of this works pretty much fine, but sometimes when I start drawing a line with the mouse left button held down, the box div becomes "grabbed". After this, while dragging the mouse with the left button still down, the boxes are not filled when hovering over them. Then when I release the mouse it starts drawing. It's as if the behavior is toggled after the accidental "grabbing", but on the next mousedown it starts acting normally again.
This is probably harder to explain than to see it for yourself, so below is my code as well as a link to a corresponding codepen.
I've tried googling to find out how I can remove this "grabbing" behavior, but I haven't really found anything, probably because I don't even know what keywords to search for.
Can somebody explain what's happening and provide some info on how I can fix this?
Etch-a-Sketch Codepen
const GRID_SIZE = 50;
for(let i = 0; i < GRID_SIZE * GRID_SIZE; i++){
const container = document.getElementById('container');
let div = document.createElement('div');
div.classList.add('box');
container.appendChild(div);
}
function fillBox(e){
this.classList.add('filled');
}
function clearGrid(){
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => box.classList.remove('filled'));
}
function startDrawing(){
// console.log("start drawing");
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => box.addEventListener('mouseover', fillBox));
}
function stopDrawing(){
// console.log("stop drawing");
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => box.removeEventListener('mouseover', fillBox));
}
const container = document.querySelector('#container');
container.addEventListener('mousedown', startDrawing);
container.addEventListener('mouseup', stopDrawing);
const button = document.querySelector('#clear-grid-btn');
button.onclick = clearGrid;
#container{
width: 500px;
display: grid;
grid-template-columns: repeat(50, 10px);
grid-template-rows: repeat(50, 10px);
border: solid;
border-color: black;
margin:auto;
}
.box{
width: 10px;
height: 10px;
}
.box:hover{
background-color: blue;
}
.filled{
background-color: blue;
}
#clear-grid-btn{
display:block;
margin:auto;
margin-top: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="etch-a-sketch.css">
</head>
<body>
<div id="container"></div>
<button id="clear-grid-btn">Clear grid</button>
</body>
<script src="etch-a-sketch.js"></script>
</html>
What happens here is that the default behavior of a mousedown + mousemove is to initiate a grab.
Certainly, at some point, the browser will select some content in the page and start grabbing it.
The solution to avoid this is to tell the browser that your code does handle the event and should thus not perform its usual behavior. You can do so by calling the Event::preventDefault() method:
const GRID_SIZE = 50;
for(let i = 0; i < GRID_SIZE * GRID_SIZE; i++){
const container = document.getElementById('container');
let div = document.createElement('div');
div.classList.add('box');
container.appendChild(div);
}
function fillBox(evt){
evt.preventDefault(); // tell the browser we handle that event
this.classList.add('filled');
}
function clearGrid(){
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => box.classList.remove('filled'));
}
function startDrawing(evt){
evt.preventDefault(); // tell the browser we handle that event
// console.log("start drawing");
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => box.addEventListener('mouseover', fillBox));
}
function stopDrawing(evt){
evt.preventDefault(); // tell the browser we handle that event
// console.log("stop drawing");
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => box.removeEventListener('mouseover', fillBox));
}
const container = document.querySelector('#container');
container.addEventListener('mousedown', startDrawing);
container.addEventListener('mouseup', stopDrawing);
const button = document.querySelector('#clear-grid-btn');
button.onclick = clearGrid;
#container{
width: 500px;
display: grid;
grid-template-columns: repeat(50, 10px);
grid-template-rows: repeat(50, 10px);
border: solid;
border-color: black;
margin:auto;
}
.box{
width: 10px;
height: 10px;
}
.box:hover{
background-color: blue;
}
.filled{
background-color: blue;
}
#clear-grid-btn{
display:block;
margin:auto;
margin-top: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="etch-a-sketch.css">
</head>
<body>
<div id="container"></div>
<button id="clear-grid-btn">Clear grid</button>
</body>
<script src="etch-a-sketch.js"></script>
</html>

Categories

Resources