I'm using AHAH to load a piece of HTML after the document is ready. There's a button in that chunk of HTML I would like to apply a .click event to. I'm having trouble applying that event after the HTML is loaded. The call back is very generic and is used by other parts of the page so I would prefer not to fill it up with specific code. Any ideas?
This is what the live
method was built for.
Your best bet is to either use that, or add an event listener to your containing element (or even to body
). Live
is great for events that bubble. Event listeners are the solution to ones that do not.
As others are pointing out, you want to consider using $.live()
, which will handle events for all pre-existing DOM elements, as well as any added later down the road. For instance, suppose the block of HTML you're loading in has a set of links containing the classname "foo," all of which should respond in a specific way when clicked:
$(".foo").click(function(){
// I don't do anything to dynamicall-added elements
});
This example will only apply to pre-existing items containing the classname "foo." To handle current, and future elements, we should do the following:
$(".foo").live("click", function(){
// I handle both present, and future elements
});
Now anything added at any time will be handled by this if it contains the classname "foo". This works great for situations like yours where large blocks of html will be inserted into the DOM later in the page's lifecycle.
As everyone said the .live() method has been designed especially for this purpose and you're talking about the click event which .live() handles so go ahead and use that, it'll be the easiest/fastest way to accomplish this.
Just a suggestion though, you're saying you have a pretty generic callback function and for a very similar situation I couldn't use .live() (I had to do some fairly complex processing after) so I added flexibility to it by adding a parameter to the initial call so that calling code could specify a custom callback. something along those lines:
callToAGenericService({url: '...', target: someId, callback: function myCustomCallBack (xhr) {
console.log('Custom callback');
console.dir(xhr);
}});
and the generic service generic callback was modified to be something along those lines:
function genericServiceCallback(options,xhr) {
//Do the 'generic processing' of the request
// if calling code specified a custom callback, execute it
if (options.callback) {
options.callback(options,xhr);
}
}
It was obviously much more sophisticated (error and scope handling mainly) but gives an idea.