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?
You can either bind it when you generate it, e.g. if it’s generated by
$.ajax(), then it would look like this: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: