I have been using .live() in my jquery code but it some how fails when the html is generated dynamically, so is there a alternative for .live() in jquery?
-
1Update your jQuery to a recent version and use [`.on`](http://api.jquery.com/on/). – Andy Nov 04 '13 at 10:22
-
1`.live` is depreciated now :) – Richard Peck Nov 04 '13 at 10:22
-
1It's not deprecated, it's removed altogether. Anyway [the documentation](http://api.jquery.com/live/) tells about the alternative. – JJJ Nov 04 '13 at 10:23
3 Answers
Firstly, .live
is depreciated removed, and is replaced with .on
:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()
If you're generating elements "on the fly", you need to bind them to a function, and as they're not already in the DOM, you'll need to bind to the document, and delegate to the specific element:
$(document).on("event", "element", function(){
//do what you need here
});
As you've not provided any code, I can only give you a general idea as demonstrated above

- 76,116
- 9
- 93
- 147
the purpose of live is exactly to works when html is generated dynamically. Maybe you have to put your .live call inside a $(document).ready :
$(document).ready(function(){
$("class selector").live(function(e){
// your code here
})
});
and, like commented by others in the question, live() should be replaced by a new syntax you can see here : Turning live() into on() in jQuery
-
It doesn't make much sense to wrap `.live()` in a document ready event since its purpose is, as you said, to work regardless of when the target elements are created. – JJJ Nov 04 '13 at 10:27
-
Yes it makes a lot of sense : without document.ready, `$` may not be loaded. – Asenar Nov 04 '13 at 10:29
-
2
-
That's a good question I can't answer to. I know that by experience: sometimes on really slow server, $("").live() gives an error "$ is not defined", and it never does when inside a .ready – Asenar Nov 04 '13 at 10:39