Issue
I am doing the Etch-a-sketch project from odin project and so far I've been able to make the grid and apply the hover effect. I'm stuck on trying to make the child divs fit the parent div properly. I was thinking of a way to resize the child divs but could not figure it out. I also think that setting the parent div (container) and the child divs sizes to fixed numbers is giving me issues.
Any help is appreciated!
<!DOCTYPE html>
<html lang="en">
<head>
<script src="script.js" defer></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Etch-A-Sketch</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
let container = document.getElementById('container');
let squaresPerSide = prompt('Choose a number up to 100 to make a grid with that many squares on each side.');
function newGrid () {
let totalSquares = squaresPerSide * squaresPerSide
for (i = 0; i < totalSquares; i++) {
let myDivs = container.appendChild(document.createElement('div'));
myDivs.setAttribute('style', 'background-color: black; width: 10px; height: 10px; margin: 1px');
myDivs.addEventListener("mouseover", function() {
myDivs.style.backgroundColor = "red"
})
}
}
container.setAttribute('style', 'display: flex; width: 370px; flex-wrap: wrap; justify-content: center; align-items: center');
document.body.setAttribute('style', 'display: flex; justify-content: center; align-items: center; height: 100vh; margin: auto');
newGrid()
Solution
a simple solution to create the desired grid could be adding a row div
to the DOM and appending squaresPerSide
amount of squares to that div before moving to the next row div
. There will be squaresPerSide
amount of rows as well (creating squaresPerSide
* squaresPerSide
boxes).
Here is the code to better explain this:
for (i = 0; i < squaresPerSide; i++) {
const row = container.appendChild(document.createElement('div'));
for (j = 0; j < squaresPerSide; j++) {
let square = container.appendChild(document.createElement('div'));
square.setAttribute('style', 'background-color: black; width: 10px; height: 10px; margin: 1px');
square.addEventListener("mouseover", function() {
square.style.backgroundColor = "red"
})
row.appendChild(square);
}
}
Here is a fiddle to play around with: https://jsfiddle.net/s8zL9fq5/
Answered By - Talha Azhar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.