tags:

views:

130

answers:

2

hi all,

i made a simple jQuery button widget (plugin) which initializes like this:

var cmd = $(".tButton");
cmd.tButton();

is there a way to use .live for all future buttons (getting loaded via ajax)?

thx

A: 

You can, but just be careful what you are doing. If you want to automatically re-run your plugin connect code, then $.fn.live() is not what you want.

If you are attaching a few event handlers, then you can, but you need to attach it to the main collection like this:

 $.fn.yourPlugin = function(){
     this.live('click', function(){...});
 }
Doug Neiner
how do you use `$.live()`? Is it a utility function?
Russ Cam
My bad, its not `$.live()` its `$.fn.live()`
Doug Neiner
Thanks - I thought for a second there was a jQuery command I wasn't aware of!
Russ Cam
A: 

The answer to this question is No, though dcneiner's answer is great if all you're doing is handling events. If you want to make some other modifications you're out of luck.

live works by attaching the event handler to the document element. Since events bubble in js (they can be handled by parents of the clicked/mouseover'd/etc element), document has a chance to handle events from every element on the page.

Unfortunately as far as I know there's no event for when an element is created, so you couldn't automatically run a function when an element is created. jQuery's live doesn't know that the new button exists until it is clicked/mouseover'd/etc.

Adam A