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


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.