I made an etch-a-sketch for the odin project but I was told I could combine my createGrid() and updateGrid() functions using parameters. How might I go about that? The update grid function is to allow for the user to input any number and change the grid size.
const grid = document.querySelector(".gridContainer");
const userInput = document.getElementById("quantity");
const clear = document.querySelector(".clear");
const createGrid = () => {
for(let i = 0; i < 256; i++) {
const div = document.createElement("div");
div.classList.add("square");
grid.appendChild(div);
div.addEventListener("mouseenter", function () {
div.style.backgroundColor = randomColor();
});
}
};
const updateGrid = () => {
grid.innerHTML="";
grid.style.setProperty(
"grid-template-columns",
`repeat(${userInput.value}, 1fr)`
);
grid.style.setProperty(
"grid-template-rows",
`repeat(${userInput.value}, 1fr)`
);
for (let i = 0; i< userInput.value * userInput.value; i++){
const div=document.createElement("div");
div.classList.add("square");
grid.appendChild(div);
div.addEventListener("mouseenter", function () {
div.style.backgroundColor = randomColor();
});
}
};
userInput.addEventListener("change", updateGrid);
function randomColor() {
const randomRed = Math.floor(Math.random() * 256);
const randomGreen = Math.floor(Math.random() * 256);
const randomBlue = Math.floor(Math.random() * 256);
return `rgb(${randomRed}, ${randomGreen},${randomBlue})`;
}
clear.addEventListener("click", function() {
grid.innerHTML = "";
userInput.value = "";
grid.style.setProperty("grid-template-columns", `repeat(16, 1fr)`);
grid.style.setProperty("grid-template-rows", `repeat(16, 1fr)`);
createGrid();
});
createGrid();
Have createGrid
take a parameter, the number of squares to make:
const createGrid = (limit = 256) => {
for (let i = 0; i < limit; i++) {
const div = document.createElement("div");
div.classList.add("square");
grid.appendChild(div);
div.addEventListener("mouseenter", function () {
div.style.backgroundColor = randomColor();
});
}
};
const updateGrid = () => {
grid.innerHTML = "";
grid.style.setProperty(
"grid-template-columns",
`repeat(${userInput.value}, 1fr)`
);
grid.style.setProperty(
"grid-template-rows",
`repeat(${userInput.value}, 1fr)`
);
createGrid(Number(userInput.value));
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.