Jack Roscoe
Jack Roscoe

Reputation: 4313

Trouble adding event listeners via JavaScript

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);
}

Upvotes: 0

Views: 282

Answers (2)

gregers
gregers

Reputation: 13040

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/

Upvotes: 2

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

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.

Upvotes: 1

Related Questions