jQuery revisited

A couple of years ago (more like 4 really), I stumbled upon jQuery and was immensely impressed with the power and ease of use of this Javascript library. I would normally never look into things like that, but an very appealing example with one line of Javascript convinced med to spend some time on the topic.

And then I forgot about it again, until I saw that codeacademy.com also sports a jQuery introduction track.

Screen Shot 2012-12-30 at 14.28.18

During my Xmas break, I completed all of the sessions on the couch and (re-) learned heaps of useful things from this site. Some of the sessions were really simple, but nonetheless many included subtle hints that I had totally missed before.

For example, when adding HTML elements it is somewhat counter intuitive that it is just not possible to invoke standard functionality to for example add a clic handler, or maybe remove the new element again when clicked. That has to be done using a general event handler.

The example on codeacademy.com expains removing a newly added element (class “item”) like this:

You might think we could do this:

$('.item').click(function() {

and that’s not a bad idea. The problem is that it won’t work—jQuery looks for all the .items when the DOM is loaded, so by the time your document is ready, it’s already decided there are no .items to .remove(), and your code won’t work.

For this, we’ll need a new event handler: .on(). You can think of .on() as a general handler that takes the event, its selector, and an action as inputs. The syntax looks like this:

$(document).on('event', 'selector', function() {
Do something!

This is something I have never understood before, and probably wasted hours trying to figure out in wane. I tip my hat for the Codeacademy team behind this extraordinary effective, yet simple and easy to use training concept.