-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
53 lines (45 loc) · 1.42 KB
/
script.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
const gridContainer = document.querySelector("#grid-container");
const resetButton = document.querySelector("#reset-button");
function setDefaultGrid() {
setGridSize(16);
fillGrid(16);
}
function setGridSize(size) {
gridContainer.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
}
function fillGrid(size) {
for (let i = 0; i < size * size; i++) {
const gridElement = document.createElement("div");
gridElement.classList = "grid-element";
gridElement.addEventListener("mouseover", changeColor);
gridContainer.appendChild(gridElement);
}
}
function changeColor(e) {
const randomR = Math.floor(Math.random() * 256);
const randomG = Math.floor(Math.random() * 256);
const randomB = Math.floor(Math.random() * 256);
e.target.style.backgroundColor = `rgb(${randomR}, ${randomG}, ${randomB})`;
}
function changeSize() {
let newSize = prompt("Enter new size");
if (newSize !== null) {
newSize = parseInt(newSize);
if (newSize < 1 || newSize > 64 || Number.isNaN(newSize)) {
alert("Enter a number from 1-64 range");
changeSize();
} else {
clearGrid();
setGridSize(newSize);
fillGrid(newSize);
}
}
}
function clearGrid() {
const gridArray = Array.from(gridContainer.childNodes);
gridArray.forEach((element) => {
gridContainer.removeChild(element);
});
}
window.addEventListener("load", setDefaultGrid);
resetButton.addEventListener("click", changeSize);