I can't set the "onclick" attribute of an element in JS

35 Views Asked by At

I'm working in vanilla JS. Here is my function as of now

function displayQueue() {
    queueDiv.innerHTML = "";
    for (var i = 0; i < queue.length; i++) {
        let newDiv = document.createElement("div");
        newDiv.id = i;
        var playIcon = document.createElement("img");
        playIcon.id = "P" + i;
        playIcon.src = "icons/play-solid.svg";
        // this wont work:
        playIcon.onload = function() {
            playIcon.onclick = playIconFunc;
        }
        newDiv.appendChild(playIcon);
        if (queueNames[queue[i]].length > 15) {
            newDiv.innerHTML += queueNames[queue[i]].slice(0, 15) + "...";
        } else {
            newDiv.innerHTML += queueNames[queue[i]];
        }
        let deleteIcon = document.createElement("img");
        deleteIcon.src = "icons/x-solid.svg";
        newDiv.appendChild(deleteIcon);
        queueDiv.appendChild(newDiv);
    }
}

I have tried setting it to an anonymous function, I have tried it without the "onload" thing first. I have tried it as let and var. To no avail. What could I be doing wrong? PS: I will be more than happy to provide more of my code if needed.

0

There are 0 best solutions below