Quick Reach
The live() method
The live method was used to attach one or more event handlers to the specified element and as the event(s) occur it executes the given function. We used “was” in the above statement as the live() method firstly deprecated in version 1.7 of jQuery library and later on removed from version 1.9.
So if you include the latest library of jQuery, the live() method will not work.
The handlers attached with the live() method executes for current elements as well as future elements added that matches the specified selector.
See an example of live method
For example, you have a Div with paragraphs. The paragraphs have event handlers attached to it. Your web page also allows creating the new paragraphs within that div using the JavaScript. You want to attach the same event handlers with those paragraphs that are created later. You could use jQuery live method for that purpose.
Syntax of live() method
Following was the syntax of jQuery live method:
$(selector).live(event,data,function)
e.g.
$(“div”).live(“click”, function_name)
$(“p”).live(“mouseenter”, function_name)
If you want to attach multiple events, then separate it with space as below:
$(“div”).live(“click mouseleave”, function_name)
The example below shows how you can do it with the live() method.
Example of $.live method with child in future
Following example shows how to use the live method. As you click on the text “Add new paragraph”, a child paragraph will be created. As you click both, the parent and created child paragraphs, an alert will be shown.
You can create any number of paragraphs at the run time and each paragraph would have an event handler attached to it, that will show an alert as you click on it.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#livediv').live('click', livefunction);
$("#addpara").click(function(){
$("<p>The new paragraph, or child element of Div with ID=livediv</p>").insertAfter("#livep");
});
});
function livefunction() {
alert("parent or child paragraph clicked");
}
</script>
</head>
<body>
<p id="addpara">Add new paragraph</p>
<div id="livediv">
<p id="livep">Click this with live() method </p>
</div>
<div id="div2">
<p>Paragraph in div 2</p>
</div>
</body>
</html>
|
Alternative or replacement of live method
The live() jQuery method is replaced with much better and consistent jQuery on() method.
Leave A Comment?