Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery live() to initialize plugins?

Using jQuery, what's the best way to automatically initialize a plugin on all current and future elements of a specific class?

For example, say I want all <input type="text" class="datepicker" /> elements to have the jQuery UI Datepicker plugin, including any I might create at runtime.

Essentially, I want to do something like this:

$('.datepicker').live('create', function() {
    $(this).datepicker();
});

But, of course, there isn't a create event I can use.

like image 405
Chris Fulstow Avatar asked Apr 13 '10 08:04

Chris Fulstow


2 Answers

You can use the .livequery() plugin for this, reports of it's death due to .live() have been greatly exaggerated :)

.live() listens for event to bubble so it serves a slightly different purpose. With .livequery() you'd achieve what you want like this:

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

This will run on current and future .datepicker elements.

like image 194
Nick Craver Avatar answered Oct 13 '22 00:10

Nick Craver


From what I understand you are after creating a custom even. which is like this:

$('.datepicker').bind('foo', { 'bar'  : 'bam'  }, function(e) 

  { 

    $(this).datepicker(); 

  });   

$('.datepicker').trigger('foo');

hope this helps

like image 32
Ali Habibzadeh Avatar answered Oct 13 '22 01:10

Ali Habibzadeh