Currently, I'm immersed in the Etch A Sketch project as part of my journey through The Odin Project. Using DOM manipulation, I successfully created a grid and displayed it on the screen. Now, my aim is to allow users to resize the grid by removing the existing one and replacing it with a new grid based on their input.
The challenge arises when I realize that the elements associated with the grid creation are not easily accessible due to scoping issues. I attempted to remove the vertical boxes using `verticalBoxes.remove()` within the `resizeGrid()` function, but it failed since this action wasn't in the global scope. My next approach involved removing the container within `resizeGrid()` and creating a new one, which led to declaration conflicts resulting from duplicate variables.
<!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="styles.css">
<script src= "scripts.js" defer></script>
</head>
<body>
<h1>Etch A Sketch</h1>
<div id= "container"></div>
<div id= "grid-size">
<button type="confirm" id= "resize-button">Resize Grid</button>
</div>
</body>
</html>
#container {
margin: auto;
max-width: 500px;
max-height: 500px;
}
h1 {
text-align:center;
}
.row {
display:flex;
height: auto;
}
.column {
flex: 1;
width: 100%;
aspect-ratio: 1;
border: 1px solid black;
}
.resize-button {
display: inline-block;
width:50px;
height:50px;
}
let container = document.querySelector("#container");
const button = document.querySelector("#resize-button")
function createGrid(num) {
for (let i = 0; i < num; i++) {
let horizontalBoxes = document.createElement("div");
container.appendChild(horizontalBoxes);
horizontalBoxes.classList.add("row");
for (let y = 0; y < num; y++) {
let verticalBoxes = document.createElement("div");
horizontalBoxes.appendChild(verticalBoxes);
verticalBoxes.classList.add("column");
verticalBoxes.addEventListener('mouseover', colorChange);
}
}
}
function colorChange () {
this.style.backgroundColor = "black"
}
createGrid(16);
function resizeGrid(newSize) {
newSize = prompt("What size would you like the grid to be? (1-100)");
createGrid(newSize);
}
button.addEventListener('click', resizeGrid);