Hacker News new | past | comments | ask | show | jobs | submit login

I haven't looked at Live events yet, is there anywhere I can read through a rundown of what they offer?



In a nutshell you can bind to selectors dynamically - so if content gets added to the document that matches an existing Live binding, jQuery will go ahead and create the binding for you. It didn't work with all event types in previous versions of jQuery; now it seems that they're essentially all covered.

See here: http://api.jquery.com/live/


That's a good explanation, but its not actually that jQuery automatically binds events to the newly inserted elements, its that it takes advantage of Javascript's event bubbling to match the selector at the highest level it can.

Basically, if you had HTML like this:

    <div>
        <p>
            <span>Hello World</span>
        <p>
    </div>
and the user clicks on the span, Javascript will raise a click event not only for the span but for each of its parents (p, div, body and html).

jQuery's live events take advantage of this by "trapping" the click event (or blur, focus, etc) at the highest level. This leads to 2 distinct advantages:

1) Elements inserted into a page after the script is initialized don't need to have events bound to them. (this is what defen was referencing)

2) You don't have to bind a callback to every single element.

The second can pay dividends even if there is no dynamically inserted content. For instance, lets say you have a table with 1000 cells and you want to make them editable when the user clicks on them.

Traditionally, you would do something like this:

    $('td').click(function () { makeCellEditable(this); } );
Although this would work, binding 1000 callbacks, one to each td element, will seriously impact browser performance.

With live events the syntax is very similar:

    $('td').live('click', function () { makeCellEditable(this); } );
The difference is we've only bound 1 event, so the browser's performance will not be adversely affected.

Hope that helps.


Awesome! I didn't know how it actually worked. Thanks a lot!


.live() : DOM event handling :: CSS : DOM styling




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: