3

Hello I do have following code sample in which Im trying to give each element different onClick functionality :

for (var i = 0; i < sizex; i++) {
        for (var j = 0; j < sizey; j++) {
            var canvas = document.createElement("CANVAS");
            var id = i * 10 + j;
            canvas.id = "canvas" + id;
            canvas.width = 25;
            canvas.height = 25;
            canvas.style = "border:1px solid black";
            canvas.onclick = function() {
               canvasClicked(id);
            };

            document.body.appendChild(canvas);
        }
    }

problem is its always called with id = sizex * 10 + sizey

who can I pass parameter of canvasCliced to function so this function is "different" for each canvas?

1
  • 1
    Closures my friend, learn them, love them! Commented Apr 3, 2014 at 20:11

1 Answer 1

2

Use a closure.

Change your click handler from

canvas.onclick = function() {
     canvasClicked(id);
};

to form a closure, where in the scope of the variable would be accessible.

canvas.onclick = function(nId) {
    return function() {
       canvasClicked(nId);
    }
}(id);
Sign up to request clarification or add additional context in comments.

Comments

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.