views:

31

answers:

1

I'm writing some javascript using jQuery to call a method on all nodes with class datepicker.

Here's what I have:

$('.datepicker').my_method();

This works as expected - it calls my_method.

However, I want to be able to call my_method on all new nodes that are inserted into the DOM with the class datepicker.

I want similar functionality to the .live method, without specifying an eventType.

How do I go about this?

+4  A: 

This is what the .livequery plugin is for :)

You use it like this

$('.datepicker').livequery(function() {
  $(this).my_method();
});

Alternatively, you can re-run your plugin when you're loading elements, say in the case of $.ajax(), like this:

$.ajax({
  //options..
  success: function(data) {
    $("#elementId").html(data);
    $(".datepicker", data).my_method();
  }
});

This method only runs on .datepicker elements in the response, not existing ones...so it's only running/doing the minimal amount of work. This is the most efficient approach in terms of wasted observation code/processing, etc...but it's not always an option.

Nick Craver
Nice! Went with `livequery` as I wasn't inserting with AJAX. Ta :)
nfm