JSFiddle - React, Tailwind, and code Playground
HTML
<img id="elemImage" src="https://www.espritterroirs.fr/wpsacco/wp-content/uploads/coeur-150x150.png" name="image" width="150" height="120" />
<div id="layer2" style="">
<button id="populate" data-running="false" onclick="populate()">Coeur aléatoire</button>
<input type="text" readonly id="nbr" />
</div>
<div id="layer3" style="">
<button onclick="effacer()">Effacer tout</button>
</div>
CSS
#elemImage{
display: none;
}
#layer2 {
z-index: 99999;
}
td {
height: 120px;
width: 150px;
border: none;
}
JavaScript
let increment = 0,
posXY = [];
function createTable() {
Table = document.createElement('table');
for (i = 0; i < 10; i++) {
line = document.createElement('tr');
for (j = 0; j < 10; j++) {
cell = document.createElement('td');
cell.id = "cell" + i + "_" + j;
line.appendChild(cell);
}
Table.appendChild(line)
}
document.body.appendChild(Table);
}
createTable();
function clonePic() {
// recuperation de la resolution de l'ecran chez l'utilisateur
largeur = window.innerWidth;
hauteur = window.innerHeight;
// positionnement aleatoire
cellpos = posXY.pop();
// recuperation de l'element div servant a afficher l'image
ImageHeart = document.getElementById("elemImage").cloneNode(true);
// ajustement de l'attribute style, notament left et top
ImageHeart.style.width = "150px";
ImageHeart.style.height = "120px";
//elementDivImage.style.Zindex=increment++;
ImageHeart.id = 'DivCoeur' + increment;
ImageHeart.style.display = "inline-block";
document.getElementById('cell' + cellpos).appendChild(ImageHeart);
}
function populate() {
run = document.getElementById('populate').dataset.running;
if (run == "true") {
return false;
}
document.getElementById('populate').dataset.running = "true" ;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
posXY.push(i + '_' + j);
}
}
posXY.sort(() => Math.random() - 0.5);
maxhearts = 10;
nbrhearts= Math.ceil(Math.random() * maxhearts);
for (p = 0; p < nbrhearts; p++) {
clonePic();
}
document.getElementById('nbr').value=nbrhearts;
}
function effacer() {
allhearts = document.querySelectorAll('[id^=DivCoeur]');
if (allhearts.length > 0) {
for (var heart of allhearts) {
heart.parentNode.removeChild(heart.parentNode.firstChild);
}
document.getElementById('populate').dataset.running="false";
document.getElementById('nbr').value="";
}
}