views:

20

answers:

2

I'm trying to attach a jQuery plugin to a dynamically generated button. I've tried the following with no success:

$('.myButton').live('click', function() {
    $(this).file().choose(function(e, input) {
        // ...
    });
});

I guess this doesn't work as the plugin needs binding before click.

So I tried...

$('.myButton').load(function() { ... });

and (getting desperate now)...

$('.myButton').live('load', function() { ... });

What method can I use to bind a newly generated button before the user clicks on it?

+1  A: 

you need to add the code:

    $('.myButton').live('click', function() {
        $(this).file().choose(function(e, input) {
        // ...
        });
    });

AFTER you've dynamically added your button (so basically add it in the routine that adds the dynamic button).

jim

jim
that's a good point. Do you think actually I should be doing that with all my dynamic content instead of using live()?
fearofawhackplanet
fearofawhackplanet - i think nick's use of .livequery should sort out most of the edge cases that you are encountering and where it's not appropriate, then do it inside the dynamic routine.
jim
+1  A: 

You can either bind it when you generate it, e.g. if it's generated by $.ajax(), then it would look like this:

$.ajax({
  //options...
  success: function(data) {
    //do stuff
    $(".myButton", data).file().choose(...);
  }
});

The important part there is the , data, we're giving the selector a context to search it, so it's only finding buttons that were loaded in the response. This same technique applies to the success methods on other $.ajax() shorthand versions as well.


If that's not an option, then there's a not-as-performant-route available. You can use the .livequery() plugin which actively looks for and acts upon new elements, whatever the source. Your code would look like this in that case:

$(".myButton").livequery(function() {
  $(this).file().choose(...);
});
Nick Craver