views:

41

answers:

3

I'm sure this is something that AJAX gurus learn very early on, but this is the first time I've run into it. Using jQuery, I have assigned .click() handlers to certain CSS classes. However, if I reload some of the content via AJAX, the .click() handlers are not firing for that content.

It seems I have two choices:

  1. put my .click() handler assignments within a JScript function, and call it every time content is refreshed via AJAX.
  2. use onclick="" rather than jQuery within my AJAX content.

So far, it seems #1 would be the best; it's more consistent and yields smaller HTML for AJAX.

Is there another way to do it? Perhaps a different way of assigning the .click() handlers from the outset?

+1  A: 

You are looking for the live() method instead.

$('selector').live('click', function(){
  // your code.......
});

The live works for elements present now or in the future.

Sarfraz
Wow, I'm glad I asked. I had no idea that existed. Thanks!
Mark
+1  A: 

Hey,

Check out the bind or live methods, check this out: http://api.jquery.com/live/

Brian
+1  A: 

If you are using jQuery 1.4+, .live() is part of the core. If not then there is a plugin called livequery that provides the functionality you are looking for.

ryanzec