odin-etch-a-sketch/script.js

58 lines
1.8 KiB
JavaScript

const container = document.querySelector("#container");
function randomizeColor() {
const hex = "0123456789abcdef";
let output = "#";
for (let i = 0; i < 6; i++) {
output += hex[Math.floor(Math.random() * 16)];
}
return output;
}
function createGrid(size) {
for (let i = 0; i < size; i++) {
let flexbox = document.createElement("div");
flexbox.classList.add("flexbox");
for (let j = 0; j < size; j++) {
let div = document.createElement('div');
div.classList.add("block");
flexbox.appendChild(div);
}
container.appendChild(flexbox);
}
let blocks = document.querySelectorAll(".block");
blocks.forEach(block => {
block.addEventListener("mouseover", (event) => {
event.target.style.backgroundColor = randomizeColor();
});
// block.addEventListener("mouseout", (event) => {
// setTimeout(() => {
// event.target.style.backgroundColor = "#fff";
// }, 1 * 1000);
// });
})
}
createGrid(16);
function removeGrid() {
document.querySelectorAll(".flexbox").forEach(flexbox => flexbox.remove());
document.querySelectorAll(".block").forEach(block => block.remove());
}
function clearGrid() {
document.querySelectorAll(".block").forEach(block => {
block.style.backgroundColor = "#fff";
});
}
document.querySelector("button#clear").addEventListener('click', clearGrid);
document.querySelector("button#gridsize").addEventListener('click', () => {
let newGridSize = prompt("Provide new size of grid, provide one number, it will be processed as (VALUExVALUE - square grid):");
if (!isNaN(newGridSize) && newGridSize != null && newGridSize != "") {
removeGrid();
createGrid(newGridSize);
}
});