I have a project similar to an Etch-a-Sketch in progress. The main challenge I am currently facing is how to gradually darken each cell of the grid with every pass of the mouse cursor, based on the opacity of the cell being hovered over. When the grid cells are initially created, the background color is set to black and the opacity to 0. I have a function called shadeCells()
that I expect to increase the opacity by 10% for each mouseover action, but instead it just sets the opacity to 10%, and subsequent passes of the mouse do not change anything if the opacity is already at 10%.
const container = document.querySelector('.gridContainer');
const startButton = document.querySelector('.gridCreator');
function createGrid(rows = 16, columns = 16) { // Creates default grid of 16x16 on page load
total = rows * columns;
for (i = 0; i < total; i++) {
cells = document.createElement('div');
cells.classList.add('cell');
cells.setAttribute('style', 'margin: 0; padding: 0; background-color: black; opacity: 0;');
container.style.gridTemplateColumns = `repeat(${columns}, 1fr)`;
container.style.gridTemplateRows = `repeat(${rows}, 1fr)`;
container.appendChild(cells);
}
shadeCells();
}
createGrid();
function newGrid(layout) { // Prompts user for input between 2 and 100 to create new grid of a different size
const cellCount = document.querySelectorAll('.cell');
for (i = 0; i < cellCount.length; i++) {
container.removeChild(cellCount[i]);
}
do {
layout = parseInt(prompt('How many columns and rows would you like to play? Pick between 12 and 100!'));
gridSize = layout * layout;
} while ((layout < 2 && Number) || (layout > 100 && Number));
createGrid(layout, layout);
}
function shadeCells() { // Changes cell opacity on mouseover
const cells = document.querySelectorAll('.cell');
cells.forEach(cell => {
cell.addEventListener('mouseover', () => {
if (cell.style.opacity >= 0.1) {
cell.style.opacity += 0.1;
} else {
cell.style.opacity = 0.1;
}
})
})
}
startButton.addEventListener('click', newGrid);
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
margin: 0;
min-height: 100vh;
display: flex;
flex-direction: column;
}
#header {
display: flex;
flex-direction: row;
justify-content: center;
gap: 3%;
}
.headerText {
font-size: 40px;
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif
}
button {
height: 50%;
width: 7%;
margin: 0%;
align-self: flex-end;
border-radius: 10px;
border: solid black 1px;
box-shadow: 3px 3px;
}
.gridContainer {
margin: auto;
height: 600px;
width: 600px;
border: solid black 1px;
display: grid;
grid-template-columns: repeat(auto, 1fr);
}
<div id="header">
<div class="headerText">Etch-A-Sketch</div>
<button class="gridCreator">Create Grid</button>
</div>
<div class="gridContainer"></div>
(Link to CodePen: https://codepen.io/codesharingaccount/pen/xxPjrMy)