user2082422
user2082422

Reputation: 129

Adding same event listener to multiple elements with different parameter

I have stucked with this for days now.

I have a JavaScript function that creates a 10x10 table with 100 images in each td elements. At the creation of these images, I add an onclick event listener to them with a parameter of their ID number. When these images are clicked, they should pop up an alert with their ID number in content. However, the alert message shows me "[object MouseEvent]" instead. I don't have an idea what causes that. I've been searching on w3schools, stackoverflow and other blogs, but not much success so far.

This is the JS code:

function orbClicked(orb) {
    alert(orb);
}

function initField() {
    var table = document.getElementById("gameField");

    for (var i = 0; i < 10; i++) {
        var tr = document.createElement("tr");

        for (var j = 0; j < 10; j++) {
            var td = document.createElement("td");
            var orbNumber = i * 10 + j;

            var orbImage = document.createElement("img");
            orbImage.setAttribute("src", "images/orb_empty.png");
            orbImage.setAttribute("id", "orb" + orbNumber);
            orbImage.addEventListener("click", function(orbNumber) {orbClicked(orbNumber)}, false);

            td.appendChild(orbImage);
            tr.appendChild(td);
        }

        table.appendChild(tr);
    }
}

Thank you in advance for your help!

Upvotes: 0

Views: 389

Answers (1)

Pushker Yadav
Pushker Yadav

Reputation: 856

function orbClicked(orb) {
alert(orb);

}

function initField() { var table = document.getElementById("gameField");

for (var i = 0; i < 10; i++) {
    var tr = document.createElement("tr");

    for (var j = 0; j < 10; j++) {
        var td = document.createElement("td");
        var orbNumber = i * 10 + j;

        var orbImage = document.createElement("img");
        orbImage.setAttribute("src", "images/orb_empty.png");
        orbImage.setAttribute("id", "orb" + orbNumber);
        orbImage.addEventListener("click", function() {orbClicked(this.id)}, false);

        td.appendChild(orbImage);
        tr.appendChild(td);
    }

    table.appendChild(tr);
}

}

don't pass the id variable in run time function (callback), because it will not be available at run time. Just fetch the id at run time and pass , so "this.id" wil give the id of clicked image.

Upvotes: 1

Related Questions