-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
120 lines (90 loc) · 2.5 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const main = () => {
const app = document.getElementById("app");
const resetButton = createResetButtonElement();
const grid = createGridElement();
clearExistingChildren();
app.appendChild(resetButton);
app.appendChild(grid);
gridLoop();
}
const clearExistingChildren = () => {
const app = document.getElementById("app");
while (app.children.length > 0) {
for (let i = 0; i < app.children.length; i++) {
app.children[i].remove();
}
}
}
const createResetButtonElement = () => {
const resetButton = document.createElement("button");
resetButton.innerText = "reset board";
resetButton.classList.add("reset-button");
resetButton.id = "reset";
resetButton.onclick = main;
return resetButton;
}
const createGridElement = () => {
const grid = document.createElement("div");
grid.classList.add("grid-container");
grid.id = "grid";
return grid;
}
const gridLoop = () => {
let withinBounds = false;
let gridSize;
while (!withinBounds) {
gridSize = parseInt(prompt("What is the grid size you desire?"));
if (isWithinBounds(gridSize)) {
withinBounds = true;
break;
}
if (gridSize === 0) {
break;
}
}
const gridItems = createListGridItems(gridSize);
populateGrid(gridItems);
}
const isWithinBounds = (gridSize) => {
return gridSize > 0 && gridSize <= 100;
}
const createListGridItems = (gridSize) => {
listGridItems = [];
let count = 0;
for (let i = 0; i < gridSize; i++) {
for (let j = 0; j < gridSize; j++) {
dataId = `${i}, ${j}`;
gridItem = createGridItem(dataId);
listGridItems.push(gridItem);
}
}
return listGridItems;
}
const createGridItem = (dataId) => {
const gridItem = document.createElement("div");
gridItem.classList.add("grid-item");
gridItem.setAttribute('data-id', dataId);
gridItem.id = dataId;
gridItem.addEventListener("mouseover", (e) => mouseOverGridItem(e));
return gridItem;
}
const mouseOverGridItem = (e) => {
e.stopPropagation();
const currentGridItem = document.getElementById(`${e.target.dataset.id}`)
currentGridItem.style.backgroundColor = "black";
}
const populateGrid = (gridItems) => {
const grid = document.getElementById("grid");
grid.style["grid-template-columns"] = calcGridCols(gridItems.length ** (1/2));
gridItems.forEach((gridItem) => {
grid.appendChild(gridItem);
})
}
const calcGridCols = (gridSize) => {
output = "";
for (let i = 0; i < gridSize; i++) {
output += "auto ";
}
return output
}
main();