0

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);
}
Jack Roscoe
  • 4,293
  • 10
  • 37
  • 46

2 Answers2

2

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:

Performance difference between jQuery's .live('click', fn) and .click(fn)

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

Community
  • 1
  • 1
gregers
  • 12,523
  • 8
  • 46
  • 41
  • 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 Jun 08 '10 at 08:21
1

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
  • 278,309
  • 50
  • 514
  • 539
  • actually you need to use both if you are going to have some sort of cross browser compatibility. – azatoth Jun 07 '10 at 14:34