Whats the use of live in jQuery? I mean when exactly do we use it.
I was trying to add an onclick event to an anchor tag, but it was not working. Then I used:
$('#Register').live('click', function (e) {
$("#storytellerregistration").fadeIn("slow");
});
and this worked. When exactly should we use live function?
Quoting Docs:
(Emphasis mine)
Notice the
and in the futurepart, it refers to those elements that are not present but will be added in future.So you use
live()for those elements that you add dynamically/later in your page via JS/jQuery.In conclusion,
live()works for elements that are present when document was loaded and also those which are added later via JS/jQuery.Let’s assume we create a div and attach it to body:
Now since we added this element ourself later/afer page load, we will have to use
live()for such element.Note: The
live()is deprecated method and won’t work in future versions of jQuery. Start usingon()method instead 🙂