0

I am working on a simple app that simulates a chess board. Therefore I have a table with 64 squares. I would like to bind event handlers for each square by writing a single function that goes through a loop instead of writing things out 64 times. EDIT: Please note I want the handlers to return a numeric value to indicate which div was clicked. I don't need the handlers to return the content of the divs. Here is a simplified version given two clickable divs:

<div id="div0">A box</div>
<div id="div1">Another box</div>
<div id="say"></div> 

and the javascript code:

$("#say").append("Which div are you going to click? ");

function clicky() {
    var i = 0;
    while (i < 2) {
        $("#div" + i).on("click", function () {
            $("#say").append("div" + i);
        });
        i++;
    }

}

clicky();

Here is the jsfiddle.

The function almost works, that is, it binds to both divs, but it binds the same (wrong) handler to both of them. Not sure how to fix this.

2
  • 1
    jsfiddle.net/q53y3L4q/6 Commented Dec 26, 2014 at 9:17
  • For your info, you are facing closure here Commented Dec 26, 2014 at 9:23

3 Answers 3

4

Use a common class. Then you can use Class Selector (“.class”) to bind event

HTML

<div class='myDiv' id="div0">div0</div>
<div class='myDiv' id="div1">div1</div>
<div id="say"></div>

Script

$("#say").append("Which div are you going to click? ");
$(".myDiv").on("click", function () {
    $("#say").append(this.id);
});

DEMO

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

2 Comments

Have I missed something?
Not sure why the down vote. I like the use of this.id. It makes sense to me. Thanks!
0

Attaching event to 64 squares is not the right approach here. You should use event bubbling here. Attach the event to container of 64 squares. Then if the event is captured, you can figure out the event target.

Read about event bubbling from the resource: http://javascript.info/tutorial/bubbling-and-capturing

Comments

0

try this:-

$("#say").append("Which div are you going to click? ");
function clicky()
{
var i = 0;
for(i;i<=2;i++)
{
    $('#div'+i).on('click',function(){
    $("#say").append($(this).html());
    });
 }

}

clicky();

Demo

1 Comment

Using a class makes nuch more sense than a loop

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.