How to attach an event to a particular type of element for the whole life of the page in jQuery- .live()

To attach an event to a particular type of element for the whole life of the page, live() method can be used. The event attached using live() works for all similar type of elements even created after this method is called.

$("#pLive").live("click", function () {
$(this).before("<p>New paragraph added</p>");
$(this).after("<p id='pLive' style='color:green;'>New paragraph added - this is live</p>");
});

Above code will bind the click event on the “pLive” element but notice that third line is adding another html element with the same id “pLive” so this event will also raise when user will click green color this line.
We will not get this behavior in the case we would have bounded the click event with “bind()” method.

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.