I have basic HTML as below:
<!DOCTYPE html>
<html>
<head>
<title>Art Maker!</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Pixel Art</h1>
<h2>Choose Grid Size</h2>
<form id="sizePicker">
Grid Height:
<input type="number" id="inputHeight" name="height" min="1" value="1">
Grid Width:
<input type="number" id="inputWidth" name="width" min="1" value="1">
<input type="submit">
</form>
<h2>Pick A Color</h2>
<input type="color" id="colorPicker">
<h2>Design Canvas</h2>
<table id="pixelCanvas"></table>
<script src="designs.js"></script>
</body>
</html>
JavaScript below are used to:
- obtain user input: height & width
- draw grid based on height & width
- obtain HTML color picker
- fill a cell with background color based on step (3) when user click on the cell
I'm stuck at step (4). I created a function respondToClick(event) and attach it to tblRow with eventListener. It should fill the cell with background color when "click"; but it doesn't. Please advise where goes wrong.
// obtain grid size value; height & width
let height = document.getElementById('inputHeight').value;
let width = document.getElementById('inputWidth').value;
const gridHeight = document.getElementById('inputHeight');
gridHeight.addEventListener("input", function() {
height = document.getElementById('inputHeight').value;
})
const gridWidth = document.getElementById('inputWidth');
gridWidth.addEventListener("input", function() {
width = document.getElementById('inputWidth').value;
})
/ function to create canvas
const table = document.getElementById('pixelCanvas');
function createCanvas(event) {
for (let h = 1; h <= height; h++) {
const row = document.createElement('tr');
for (let w = 1; w <= width; w++) {
const cell = document.createElement('td');
cell.style.cssText = "height: 15px; width: 15px";
row.appendChild(cell);
}
table.appendChild(row);
}
}
const form = document.querySelector('form');
// bind createCanvas() to "submit"
form.addEventListener('submit', createCanvas);
// event listener to update color
let color = document.getElementById('colorPicker').value;
document.getElementById('colorPicker').onchange = function() {
color = this.value;
}
// function activated when user click on only
function respondToClick(event) {
if (event.target.nodeName.toLowerCase() === 'td') {
event.target.style.backgroundColor = color;
}
}
const tblRow = document.getElementsByTagName('tr');
tblRow.forEach(row => function() {
row.addEventListener("click", respondToClick);
});