0

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!

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Oh, I'm so happy right now that it works... This realy seems logical, I don't know why I didn' think of passing the attribute property instead. Good lesson to learn.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.