jQuery live method and its alternative

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:



$(“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.

jQuery live

Experience this example online

Alternative or replacement of live method

The live() jQuery method is replaced with much better and consistent jQuery on() method.

Was this article helpful?

Related Articles

Leave A Comment?