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

2 Answers 2

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/

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

1 Comment

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.
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.

1 Comment

actually you need to use both if you are going to have some sort of cross browser compatibility.

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.