I'm working on a piece of code that generates a grid-like arrangement of chocolate pieces based on user input for the dimensions. I want each chocolate piece to have its own unique ID (like imgPos1, imgPos2, etc.), but I'm struggling to implement this functionality. Any suggestions or recommendations for third-party frameworks like React would be appreciated.
HTML (and JS):
<html>
<body>
<div>
<form name='grid' id="grid">
<!-- Form to define the x size and y size of the grid made out of chocolate pieces -->
Desired Length: <input type='number' name='length' min=1 max=10 step=1 value=1 id="lengthInput" />
Desired Height: <input type='number' name='height' min=1 max=10 step=1 value=1 id="heightInput" />
<input type='button' value='Apply' class="button_Change" />
</form>
</div>
<div id='choc'></div>
<template>
<img id="imgPos" src="https://cdn.shopify.com/s/files/1/1061/1924/products/Chocolate_Bar_Emoji_large.png?" onclick='removeMe(this)' class='visible'>
</template>
<script type="text/javascript">
/* Script that creates the grid by cloning the chocolate image for x:length
and y:height */
// defines variables q,d,form using jquery
const d = document;
const q = (e, n = d) => n.querySelector(e);
const form = d.forms.grid;
// Listens for activity on the button depending on its state
document.querySelector('[type="button"]').addEventListener("click", (e) => {
let choc = q("#choc");
choc.innerHTML = "";
// Maxes out the values for height and length to 10 for practical reasons
if (form.height.value > 10) form.height.value = 10;
if (form.length.value > 10) form.length.value = 10;
// assigns chocolate image to length and height
for (let y = 0; y < form.height.value; y++) {
let div = d.createElement("div");
choc.appendChild(div);
for (let x = 0; x < form.length.value; x++) {
div.appendChild(q("#imgPos", q("template").content).cloneNode(true));
}
}
});
function removeMe(e) {
e.classList.remove("visible");
};
</script>
</body>
</html>
CSS
#grid {
top: 180px;
left: 350px;
position: absolute;
cursor: auto;
font-family: 'Press Start 2P', cursive;
font-size: 10px;
}
#imgPos {
display: block;
width : auto;
height: auto;
cursor: pointer;
position: relative;
width: 20px;
height: auto;
top: 0px;
left: 0px;
}
#choc {
display: grid;
grid-template-rows: 1fr 1fr;
margin-left: auto;
margin-right: auto;
top: 240px;
left: 340px;
position: absolute;
cursor: default;
}
#choc > div{
position: absolute;
width:50px;
display:block;
}
#choc > div > #imgPos{
float: left;
float: right;
clear:none;
width:50px;
display: inline-block;
}
#choc > div > #imgPos:not(.visible) {
opacity: 0;
cursor: default;
}
Here's a fiddle I made using it: