Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
89 lines (73 loc) · 2.17 KB
/
Copy pathmain.js
File metadata and controls
89 lines (73 loc) · 2.17 KB
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
const sizePrompt = document.querySelector('.grid-size-prompt');
const gridContainer = document.querySelector('.grid-container');
const columnDisplay = document.querySelector('.grid-size');
let columns;
let size;
sizePrompt.addEventListener('click', function () {
columns = window.prompt('Enter number of columns you want between 1-100');
size = columns * columns;
if (checkBounds(columns)) {
generateGrid(columns, size);
} else {
window.alert('Must be between 1-100');
}
});
function checkBounds(columnsEntered) {
if (columnsEntered >= 1 && columnsEntered <= 100) {
return true;
} else {
return false;
}
}
function generateGrid(numberOfColumns, numberOfBoxes) {
const containerWidth = 800;
let boxSize = containerWidth / numberOfColumns;
columnDisplay.textContent = numberOfColumns;
if (gridContainer.children.length === 0) {
console.log('draw');
for (let i = 1; i <= numberOfBoxes; i++) {
const newBox = document.createElement('div');
newBox.classList.add('grid-box');
newBox.setAttribute('id', `box-${i}`);
newBox.style.width = `${boxSize}px`;
newBox.style.height = `${boxSize}px`;
gridContainer.appendChild(newBox);
}
draw();
} else {
replaceExistingGrid();
}
}
function replaceExistingGrid() {
let childElement = gridContainer.lastElementChild;
while (childElement) {
gridContainer.removeChild(childElement);
childElement = gridContainer.lastElementChild;
}
generateGrid(columns, size);
}
function randomColor() {
let randomizer = () => Math.floor(Math.random() * 256);
return (rgb = `rgb(${randomizer()}, ${randomizer()}, ${randomizer()})`);
}
function addColor() {
let hoveredBoxId = getBoxId(this);
let hoveredBox = document.getElementById(hoveredBoxId);
hoveredBox.style.background = randomColor();
console.log(hoveredBoxId, hoveredBox);
}
function getBoxId(box) {
let boxId;
return (boxId = box.id);
}
function draw() {
if (gridContainer.children.length !== 0) {
//get all boxes
let boxes = document.querySelectorAll('.grid-box');
boxes.forEach((box) => {
box.addEventListener('mouseover', addColor);
});
}
}
generateGrid(16, 256);
draw();