jquery 1.9 – adding handlers after dom load

Just started a project using jQuery 1.9 and immediately got stuck with adding handlers to elements that are created after the dom has loaded, i simply did:

Prior to jQuery 1.9, adding a click (or any handler for that matter) to an element after the DOM has loaded used to be a matter of using live(), or delegate() or bind() or… zzzz…. all great methods but they have kept changing along the way as jQuery has matured, meaning upgrading a jQuery library on a site could potential kill certain functionality. *

the “old” way

[code language=”js”]
$(‘#theElement’).on(‘click’, function()
{
doSomething();
});[/code]

The jQuery 1.9 way to assign a handler after the dom has loaded…

This code did not make sense at first, i initially thought it was not very intuitive. But after around a minute or two, it makes perfect sense, and i can see whey they have chosen this method:

[code lang=”js”]
$(document).on(‘click’, ‘#theElement’, function()
{
doSomethingElse();
});
[/code]

I have used document in the above example, but it simply needs to be a parent of the actual select you want (#theElement in this case).

It works like this:

jQuery is saying something like:

Look inside element document, for element #theElement, and bind this function to it…

Great stuff. No more using third party plugins to achieve what should be a built-in feature :) (though .live() did get adopted for a while)

* there is a jquery migration script that restores deprecated functionality, which is great for fixing the scenario i described, but i’m not sure i like it, i would prefer to leave the old sites using their versions of jQuery, and build new sites with the latest build of it.




3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *