I’m sorry if this is a repeated question and I’d like some help cause I’m a noob. I created a grid. But every time I enter a different number, it uses a different total amount of pixel. I want the height and the width of the body that contains grid to stay exactly the same size no matter what the number of grid is.
https://moonsol124.github.io/ETCH-A-SKETCH-TOP-PROJECT-/
here is what I made.
java:
JavaScript
x
13
13
1
function createGrid(maxGrid = 16) {
2
for (let i = 0; i < maxGrid; i++) {
3
const divRow = document.createElement('div');
4
divRow.classList.add('div-row');
5
for (let j = 0; j < maxGrid; j++) {
6
const div = document.createElement('div');
7
div.classList.add('div-style');
8
divRow.appendChild(div);
9
}
10
body.appendChild(divRow);
11
}
12
addColorOnGrid();
13
}
css:
JavaScript
1
13
13
1
.div-row {
2
display: flex;
3
flex-direction: column;
4
}
5
6
.div-style {
7
width: 25px;
8
height: 25px;
9
flex: 1 1 auto;
10
background-color: RGB(0, 0, 0);
11
border: solid 3px RGB(255, 255, 255);
12
}
13
html:
JavaScript
1
10
10
1
<body>
2
<div class="btn-group">
3
<button class="btn" id="grid-button">Enter number of grid</button>
4
<button class="btn" id="reset-button">Reset</button>
5
</div>
6
<div class="grid-body">
7
8
</div>
9
</body>
10
please tell me if my approach is wrong. thanks for your help.
Advertisement
Answer
I think this will help to you solve your problem I just add these parts
JavaScript
1
3
1
divRow.appendChild(document.createElement("div"));
2
document.getElementById('ac').appendChild(divRow);
3
it access the parent alement and create div inside that element
And you can pass any number here to test onLoad=”createGrid(6)”
JavaScript
1
32
32
1
function createGrid(maxGrid) {
2
3
for (let i = 0; i < maxGrid; i++) {
4
5
const divRow = document.createElement("div");
6
divRow.classList.add('div-row');
7
8
for (let j = 0; j < maxGrid; j++) {
9
const div = document.createElement('div');
10
div.classList.add('div-style');
11
divRow.appendChild(div);
12
}
13
14
divRow.appendChild(document.createElement("div"));
15
document.getElementById('ac').appendChild(divRow);
16
}
17
18
}
19
20
function popup() {
21
22
let val = prompt("Please enter value here");
23
24
const div = document.getElementsByClassName("div-style");
25
26
for(i = 0; div.length > 0; i++){
27
div[0].remove()
28
}
29
30
this.createGrid(parseInt(val));
31
32
}
JavaScript
1
12
12
1
.grid-body {
2
display: flex;
3
flex-direction: row;
4
}
5
6
.div-style {
7
width: 25px;
8
height: 25px;
9
flex: 1 1 auto;
10
background-color: RGB(0, 0, 0);
11
border: solid 3px RGB(255, 255, 255);
12
}
JavaScript
1
9
1
<body onLoad="createGrid(6)">
2
<div class="btn-group">
3
<button class="btn" id="grid-button" onClick="popup()">Enter number of grid</button>
4
<button class="btn" id="reset-button">Reset</button>
5
</div>
6
<div class="grid-body" id="ac">
7
8
</div>
9
</body>