/
script.js
70 lines (60 loc) · 2.05 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// queryselectors
const container = document.querySelector('#div-container');
const boxes = document.querySelectorAll('#div-container');
const buttons = document.querySelectorAll('#buttons')
// variable to select color mode, 1 = white, 2 = random
let colorMode = 2;
//variable for the grid size, 16 is default
let gridSize = 16;
//function to reset the grid
function resetGrid(){
let gridBox = document.querySelectorAll(".box");
gridBox.forEach((div) => {
div.parentNode.removeChild(div);
});
}
// function to create the grid
function createGrid(n){
for (let i = 0; i < n*n; i++){
const div = document.createElement('div');
div.classList.add('box')
container.appendChild(div)
}
container.setAttribute('style', `grid: repeat(${n}, auto) / repeat(${n}, auto)`);
}
// function to select a random color
function randomColor () {
let r = Math.floor(Math.random()*256);
let g = Math.floor(Math.random()*256);
let b = Math.floor(Math.random()*256);
return `rgb(${r},${g},${b})`
}
//make the color change when hovering over the boxes
boxes.forEach((box) => {
box.addEventListener('mouseover', (e) => {
if (colorMode === 1){
e.target.setAttribute('style', `background: white; opacity: 1;`)
} else if (colorMode === 2){
e.target.setAttribute('style', `background-color: ${randomColor()}; opacity: 1;`);
} else if (colorMode === 3){
e.target.setAttribute('style', `background: black; opacity: 1;`)
}
});
});
// eventlisteners for the buttons to change color and create new grid
buttons.forEach((button) => {
button.addEventListener('click', (e) => {
if (e.target.id === 'white'){
colorMode = 1;
} else if (e.target.id === 'random'){
colorMode = 2;
} else if (e.target.id === 'black'){
colorMode = 3;
} else if (e.target.id === 'newGrid') {
gridSize = prompt("Choose a grid size", "16")
resetGrid();
createGrid(gridSize);
}
})
})
createGrid(gridSize);