I wish to dynamically create a row of 4 buttons with an .onclick function within dynamically created div. This works perfectly well within a single div, however when attempting to create the buttons inside the nested div, only the buttons created in last div are functioning properly.
I have found questions relating to using var in for loops creating issues, but this doesn't seem to be the case here. I've tried assigning a separate function to .onclick to no avail, and just need to get it sorted!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="entries">
</div>
</body>
<script>
let synth = window.speechSynthesis;
let createButton = function (pCat, index, phraseDivIndex) {
let button = document.createElement("button");
button.innerText = pCat[index];
button.className = "entry";
button.onclick = function () {
synth.speak(new SpeechSynthesisUtterance("boo")); //speak phrase from json
}
document.getElementsByClassName("phraseDiv")[phraseDivIndex].appendChild(button); //adds buttons to newly created div for focus management.
}
let populateEntries = function () {
let phraseDivIndex = -1;
let pCat = ["one", "two", "three", "four", "five","six","seven","eight","nine"];
for (let i = 0; i < pCat.length; i++) {
if (i % 4 == 0) {
phraseDivIndex++;
document.getElementById("entries").innerHTML += "<div class=phraseDiv tabindex = 0 class = 'catRow'></div>";
}
createButton(pCat, i, phraseDivIndex);
}
}
//create buttons
populateEntries()
</script>
Outcome of code: Only the last row of buttons created have an .onclick event attached to them. That is a problem!
*edit: array index
.innerHTML +=requires a DOM read and write. Store that in avar results = '';that youresults += 'innerHTMLCodeHere';thenElement.innerHTML = results;. Of course, I don't even recommend.innerHTMLto create DOM Elements most of the time, since they have to be added to the DOM before you can attach Events to them.document.createElement(tag)is how to create... then it's likeElement.className = 'class1 class2 class3'; Element.tabIndex = -1;and the like.Element.onclick = funciton(){ /* do stuff */ }; OtherElement.appendChild(Element). Just advice.