jQuery 1.3 Live

Incidentally, I was hacking on some javascript and also upgrading to jQuery 1.3 as I had enough tuits. I had a small problem where I was adding click event handlers to some elements.

To add click events to elements; for instance, a link, I would do:

function activateLinks() {
    $('.my-links').click(function() {
        alert('a link was clicked');
        return false;
    });
}
 
$(document).ready(function() {
    // attach event to linkswith className my-links
    activateLinks();
});

The problem I had was that, when I created new elements (dynamically) that needed the same event, they would not get events attached to them automagically, as I would have to re-call the activateLinks(); function to re-initialize/attach the event to the new elements. I did not really like doing this as it seemed a bit repetitive so I decided to consult the jQuery docs and while clicking around my eyes caught something! “What is this live() thingy doing here!?” I never saw that before and noticed the Added in jQuery 1.3 tag. As it turns out; this (jQuery Live Events) was exactly what I needed. What it does is allow you attach the behaviours to elements even if they are not in the DOM yet. So now my code looks like this:

function activateLinks() {
    $('.my-links').live('click', function() {
        alert('a link was clicked');
        return false;
    });
}
 
$(document).ready(function() {
    // attach event to linkswith className my-links
    activateLinks();
});

OK. It’s a small change, but when I add new elements I don’t have to call the activateLinks() function any more as this only need to be called once on document.ready() and it will listen for future elements. In fact I could refactor the code further by getting rid of the extra function but I like putting things in their own container and leaving the document.ready() bit only for initializing. OCD? Maybe? ;)

I’m liking jQuery even more now. :)


About this entry