Attaching jQuery event handlers to elements that don’t yet exist

If you’ve used jquery, you’ll be used to attaching click events etc to items:

// for <a class="delete" href="{url}">, get user confirmation
// before navigating off to {url}

$('a.delete').click(function () {
    return confirm('Really?');

Sometimes though, the items you want to attach behaviours to don’t exist yet (e.g. because they’re created and destroyed dynamically in response to UI interaction).

You could attach the behaviour at the point you create the new element, but if you’re doing that in several places, you’ll have the same code in various places. Plus, your implementation of the behaviour for one kind of element will be buried inside the implementation of the behaviour of some other kind of element (or refactored into a function in some more public scope than it ought to be).

It turns out that jquery has a method .on() which allows you to attach event handlers to elements that may or may not yet exist:

$('body').on('click', 'a.delete', function () {    return confirm('Really?');});

The documentation explains how this works (attaching the handler to some parent element — the body element in the above example — and using browser event bubbling to catch events originating on the selected children).

It’s quite nice, you end up with quite a clean pattern whereby you create elements with a CSS class for which you have previously defined the behaviour using .on().


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: