JQuery's live(): an alternative to $(document).ready

Last updated:

You might have noticed that, if you define any event listeners on a jQuery selector, it doesn't work unless you wrap the whole thing with $(document).ready(function(){.

That's basically telling jQuery to wait until the whole page has been loaded before trying to assign the event listener to the elements matched by your selector.

This is especially noticeable, for example, when you do some styling via javascript.

Since we are telling jQuery to only act on it the moment the whole document is ready, last-minute styling with javascript will probably not get done before the user sees the page; what you get then is that ugly effect whereby a element gets shown to the user both as it was before styling and after the javascript styling has kicked in.

You don't absolutely need to wait for the whole DOM(domain object model) to have been loaded to do it though.

There's a way to attach listeners to elements that haven't been created yet.

Using live() is another way of telling javascript this(gangster speak included ):

  • you: yo javascript, listen to me, and listen to me good because I ain't gonna say it again.

  • javascript-engine: yes sir. Whatever you command, sir.

  • you: you see, I'm tired of having to wrap all my event bindings with a stupid $(document).ready(function(){ every single time.

You are pretty grown up by now so, from on, I will just tell you this: a selector, an event-type and a function. I want you to attach the function to the elements matched by the selector whenever that event is triggered.

Plus: I want you to do it as soon as the element is born; no more waiting for the whole document to be ready.

  • javascript-engine: ok.

Basically, that's what attaching a listener to a selector using line() does.


use .on() instead!

Due to some implementation weaknesses in live() and better options that have come up in jQuery since (see official jQuery documentation for live() function) , users of Jquery 1.7 + are recommended to use the on() function instead.

I've also written a small reminder on how to use JQuery's on() function, which might be of help.

Dialogue & Discussion