I made grid 16x16 with borders for each cell, then i added a button to toggle on/off borders of those cells, but it also changes overall size of my grid. how do i prevent this?
in the future i want to implement "change size" button that will increase numbers of cells but not change grid size. I'm sure i need to define grid size somehow but i don know how. Whatever i try either messes up grid size or cell size or both
here is my code
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');
// grid
function makeGrid(number) {
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).setAttribute('id', 'box');
}
}
makeGrid(16);
// drawing on hover
color.addEventListener('click', function () {
grid.addEventListener('mouseover', function (e) {
e.target.style.backgroundColor = 'black';
});
});
// erase functionality
eraser.addEventListener('click', function () {
grid.addEventListener('mouseover', function (e) {
e.target.style.backgroundColor = 'white';
});
});
// gird borders
const allBoxes = document.querySelectorAll('#box');
gridBorder.addEventListener('click', function () {
for (let i = 0; i < allBoxes.length; i++) {
if (allBoxes[i].style.border === '1px solid black') {
allBoxes[i].style.border = 'none';
} else {
allBoxes[i].style.border = '1px solid black';
}
}
});
body {
height: 100vh;
}
#grid {
display: grid;
justify-content: center;
border: 1px solid #ccc;
}
#box {
padding: 1em;
border: 1px solid black;
}
#title {
display: flex;
align-items: flex-end;
justify-content: center;
height: 230px;
}
#container {
display: flex;
height: 60%;
width: 1204px;
align-items: flex-start;
justify-content: flex-end;
gap: 20px;
}
#menu {
display: flex;
flex-direction: column;
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>
<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">Canvas Size</button>
<button id="color">Color</button>
<button id="eraser">Eraser</button>
<button id="grid-borders">Grid Borders</button>
</div>
<div id="grid"></div>
</main>
</body>
</html>