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?

Mark
  • 1,129
  • 2
  • 12
  • 25

3 Answers3

4

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
  • 377,238
  • 77
  • 533
  • 578
3

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
  • 27,284
  • 38
  • 112
  • 169
1

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

Brian Mains
  • 50,520
  • 35
  • 148
  • 257