views:

36

answers:

2

Currently I have a function which loops to create multiple HTML objects. Each time an object is created, I want to add an onClick function listener to that object so that I can trigger a function when each one is clicked.

What's the best way to do this?

Here's the code which creates my objects:

    RenderMultipleChoice:function()
{
    this.c = paper.rect(this.x, this.y, this.shapeWidth, this.shapeHeight);
}
+1  A: 

You can use addEventListener or attachEvent. Assuming paper.rect returns a DOM element:

if(this.c.addEventListener)
{
  this.c.addEventListener("click", listenerFunction, false);
}
else 
{
  this.c.attachEvent("onclick", listenerFunction);
}

There are libraries to abstract this away.

Matthew Flaschen
actually you need to use both if you are going to have some sort of cross browser compatibility.
azatoth
Thanks very much.
Jack Roscoe
+1  A: 

You might consider to use event delegation instead of adding a click listener to each created element. Then you only have one event listener on a parent, and see what element the event bubbled from. It will also magically work for elements created in the future.

jQuery has two methods to handle this for you:

  • .live() - bind event listener to the body element (has disadvantages)
  • .delegate() - bind event listener to the (parent)elements you specify (better performance)

Example:

$("#parent").delegate(".child", "click", RenderMultipleChoice);

live is an awesome function, but you should be aware of it's disadvantages:

http://stackoverflow.com/questions/1368223/performance-difference-between-jquerys-liveclick-fn-and-clickfn

http://paulirish.com/2010/on-jquery-live/

gregers
I was unaware of event delegation until now, thanks very much for suggesting this. Looks like the way to go for what I'm doing.
Jack Roscoe