const container = document.querySelector("#container"); /* header */ const header = document.createElement('h1'); header.textContent = "Etch-a-sketch"; header.setAttribute('style', 'padding: 10px;'); container.appendChild(header); /* button to change grid dimensions */ const dimensionChanger = document.createElement('button'); dimensionChanger.textContent = "Change grid size"; dimensionChanger.setAttribute('style', 'margin-bottom: 15px; margin-right: 20px;'); container.appendChild(dimensionChanger); dimensionChanger.onclick = () => { /* get user inputs */ let input = prompt("Enter the number of squares per side for new grid"); makeGrid(parseInt(input), parseInt(input)); } /* reset button */ const resetButton = document.createElement('button'); resetButton.textContent = "Reset"; container.appendChild(resetButton); resetButton.onclick = () => location.reload(); /* make grid container */ const gridContainer = document.createElement('div'); gridContainer.setAttribute("id", "griddiv"); container.appendChild(gridContainer); /* make each cell 10% darker on mouseover */ function darkenCell() { /* get current rgba of cell */ currentValue = getComputedStyle(this).getPropertyValue("background-color"); /* regex match for number values only */ const values = currentValue.match(/[\d.]+/g); /* CSS doesn't output an alpha value of 1 but rather removes the alpha value entirely at 1. do nothing if there is no alpha value (only three digits declared in rgba) */ if (values.length === 3) { return; } else { /* assigns newAlpha variable to sum of old transparency number and 0.1 (10% darker) */ const newAlpha = parseFloat(values[3]) + 0.1; /* increments cell color */ this.style.backgroundColor = 'rgba(0, 0, 0, ' + newAlpha + ')'; } } function makeGrid(rows, cols) { /* wipe existing divs */ while(gridContainer.firstChild) { gridContainer.removeChild(gridContainer.firstChild); } /* assign global CSS vars to ones passed by user */ gridContainer.style.setProperty('--grid-rows', rows); gridContainer.style.setProperty('--grid-cols', cols); /* make the cells */ for (i = 0; i < (rows * cols); i++) { let cell = document.createElement("div"); gridContainer.appendChild(cell).className = "grid-item"; /* add listeners for mouseover */ cell.addEventListener('mouseover', darkenCell); }; }; /* initialize to a default of 16x16 grid */ makeGrid(16, 16);