jQuery .live() vs .on() method for adding a click event after loading dynamic html

In this tutorial, we'll learn the difference between live() and on() method in jQuery and which is used for dynamic events after the HTML page is loaded.
Submitted by Pratishtha Saxena, on July 02, 2022

jQuery live() Method

It is an inbuilt method in jQuery. It attaches an event handler to the specified selector and when that event occurs, the live() method runs a function for the selector. This method matches the selected element which is present at that moment and also for the newly added dynamic elements in the future.

Syntax:

$(selector).live(event, function);

Note: This method was deprecated in jQuery version 1.7, and further removed. Now in resent, on() method is used instead of live().

jQuery on() Method

It is also a jQuery built-in method. Similar to the live() method, the on() method also attaches the event handlers to the selected elements.

Syntax:

$(selector).on(event, function);

Now, we'll make use of the on() method and make a dynamic list. Once the HTML page is loaded, we can add new elements to the given list just by clicking on the button.

Example:

HTML Code:

<!DOCTYPE html>

<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Title</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   <body>
      <input id="add" type="button" value="Click Here"/>
      <ol>
         <li>Item</li>
         <li>Item</li>
         <li>Item</li>
         <li>Item</li>
      </ol>
   </body>
</html>

jQuery Function:

<script>
    $(document).ready(function(){
        $('#add').on('click',function(){
            var newitem='<li>New Item</li>';
            $('ol').append(newitem);
        })
    })
</script>

Output:

Example: jQuery .live() vs .on() method






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.