odin-etch-a-sketch/script.js

90 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-11-09 18:20:28 -07:00
const container = document.querySelector(".container");
const conWidth = container.clientWidth;
const grid = document.createElement("div");
2023-11-09 20:15:53 -07:00
const gridSlider = document.querySelector("#gridSlider");
const buttons = document.querySelectorAll("button");
let colorValue = "black";
let numGrid = gridSlider.value;
let sliderLabel = document.querySelector("#sliderLabel");
2023-11-09 20:15:53 -07:00
buttons.forEach((button) => {
button.addEventListener ("click", changeColor);
});
2023-11-09 18:20:28 -07:00
function createGrid() {
const gridArea = numGrid ** 2;
const gridWidth = 100 / numGrid;
2023-11-09 15:14:02 -07:00
sliderLabel.textContent = numGrid
2023-11-09 16:31:23 -07:00
grid.classList.add("grid");
grid.style.width = gridWidth + '%';
grid.style.height = gridWidth + '%';
2023-11-09 15:14:02 -07:00
2023-11-09 16:31:23 -07:00
for (let i = 0; i < gridArea; i++){
container.appendChild(grid.cloneNode(true));
}
2023-11-09 18:20:28 -07:00
const gridItems = document.querySelectorAll(".grid");
gridItems.forEach((item) => {
2023-11-09 18:26:41 -07:00
item.addEventListener("mouseover", colorGrid);
2023-11-09 18:20:28 -07:00
});
gridSlider.addEventListener("input", getGridDimensions);
2023-11-09 15:14:02 -07:00
}
2023-11-09 16:31:23 -07:00
2023-11-09 20:15:53 -07:00
function getGridDimensions() {
numGrid = gridSlider.value;
while (container.firstChild) {
container.removeChild(container.lastChild);
}
createGrid();
}
2023-11-09 16:31:23 -07:00
2023-11-09 20:15:53 -07:00
function colorGrid() {
this.style.background = colorValue;
}
function changeColor() {
const buttonID = this.id;
switch (buttonID) {
case "rgbColor":
2023-11-09 23:17:42 -07:00
colorValue = rgbColor();
break;
case "whiteColor":
colorValue = "white";
break;
case "shade":
colorValue = "#333";
break;
case "tint":
colorValue = "#eee";
break;
case "opacity":
colorValue = "blue";
break;
case "erase":
colorValue = "transparent";
break;
default:
colorValue = "black";
break;
}
2023-11-09 20:15:53 -07:00
}
2023-11-09 16:31:23 -07:00
2023-11-09 23:17:42 -07:00
function rgbColor() {
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
let rgbCol = "rgb(" + r + "," + g+ "," + b +")";
return rgbCol;
}
2023-11-09 20:15:53 -07:00
createGrid();