13

When I add something of the class "myClass" I want to call a function on this element.

It would be something in the lines of:

jQuery(".error_message").live("load",function(){ alert("test"+this); }); 

... except this doesn't exist.

What's the best way of doing this?

4
  • How are you adding the elements to the DOM? Commented Sep 29, 2009 at 2:59
  • I load a some new html via ajax and throw it in the DOM Commented Sep 29, 2009 at 3:00
  • There are different ways I could add these elements, that's why I'd like to avoid to have a callback on these functions. Commented Sep 29, 2009 at 3:01
  • This is something I've wanted to know for Greasemonkey scripts too... Commented Sep 29, 2009 at 3:04

1 Answer 1

17

The short, direct answer to your question would be "no can do." But from your comment a few minutes ago, I see that you want to add elements in different ways and have one unified method of handling these newly added items. May I suggest another approach? Trigger custom events.

The way it would work is like this: everywhere you load the error-message element, you add one line when it's done:

 $('.error_message').trigger('load'); 

Now your .live('load'...) thing will work.

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

4 Comments

That's a very interesting answer. I'm not really sure if that's what I'm looking for... it looks a bit hacky. But I don't know jquery enought to tell hacky from amazing. So, would you say this is a good practice?
I'll vouch for it - there's also a good article on event pooling that talks about this on a document level: michaelhamrah.com/blog/index.php/2008/12/…
any idea how .live() does what it does?
This only worked for me when I used "loaded" instead of "load" v1.9.X

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.