It attaches event handlers to the specified elements and specifies the function to run when the event occurs. This method attaches delegated event handlers to the document of a page. When you use live() event, it will bind all current and future elements on the page. The live() method do not set anything on the elements directly. All event handlers are set at the document level. When live() method is called then binding is done at the document level. Only event handlers can be bound with live() method. The live() method is outdated from jQuery version 1.7 and removed in version 1.9. Use the on() method instead.
JQuery Live() Syntax
$(selector).live(event,data, function)
It has following parameters:
- event: It is required parameter which defines event types such as click or custom event names to handle event.
- data: It contains data that will be passed to the event handler.
- function: It is optional parameter which executes the function at the time the event is triggered.
JQuery Live() Example
<!DOCTYPE html> <head> <meta charset="ISO-8859-1"> <title>Live Event</title> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> </head> <h2>JQuery Live Event Example</h2> <script type="text/javascript"> $(document).ready(function(){ $("button").on("click", function(){ alert("Button is clicked!!!"); }); }); </script> <body> <button>Click</button> </body> </html>
- As shown in the above program, we have used the code inside $(document).ready which is an event which fires up when document is ready. It will run once the page document object model is ready for JavaScript code to execute.
- We have used on() method instead of live() method which specifies the function to run when the events occur.
- After executing the program, a button will get display on the browser. When you click the button, you will get alert box with specified message in that.
When you run the above example, you would get the following output: