Replace live() with on() in jQuery

The following jQuery event handler functions are basically used for attaching events to elements or selectors but are very different from each other. Before turning jQuery live() into on() function, let us first learn about the event handlers as well as their differences.

jQuery live() :
This jQuery function attaches a function handler for all the elements which matches the given selector in the current element as well as in the future or whenever some content is added dynamically to the page. This function attaches the function handler to the root document along with the given selector and data. It was introduced in jQuery 1.3 and above.
After jQuery-version 1.4, it provided support for all the events.
Earlier, it had support for only a few events like click, double click, mousedown, mouse up, mouse over, mouseout, keyup, keydown, keypress.

Syntax:

  $( selector ).live( events, data, function handler); 
  • events : One or many events separated by space, attached to the selector.
  • data : Optional data parameter passed to the function handler.
  • function handler : Function that is executed whenever the event occurs.

Note : It uses the concept of event delegation and event bubbling.

Code snippet :



$( "#container a" ).live( "click", function() {
 // some response code to the event
  alert( "GeeksforGeeks" ); 
});

The function handler was bound to the root of the document along with the selector and click event.
When the user clicks the anchor element, the event is triggered to the root of the document and matches with #container a and then executes the click event function.
Using jQuery live() in a dynamic website, the programmer need not worry about updating event handlers.
It works for both existing as well as future elements.

Code snippet :

$('a').live('click', function() { 
 alert("GeeksforGeeks") 
});

The alert function is attached to the document along with click event and a as parameters.
Whenever any event is bubbled to the root document, jQuery checks for click event and also checks for CSS selector a.
If both the conditions are satisfied, then the code inside the handler is executed effectively making the function to be very inflexible.

$( "a" ).live( "click", function( event ) {
 // It cancels the default action by this method.
  event.preventDefault();
});

Example 1:
In the following example, “click” event is attached with given “p” using this method.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html
    
<head
    <script src=
    </script
    <script
        $(document).ready(function() { 
            $("button").live("click", function() { 
                $("p").slideToggle(); 
            }); 
        });
         $('body').append(
'<p>Adding dynamic items to test live function</p>');
    </script
</head
  
<body
    
    <p>Geeks for Geeks</p
    
    <button>Press</button
    <br
    <br
    
    <div><b><h4>Clicking on the 'Press'  
      button will execute the live method(). 
      </h4></b> </div
</body
    
</html

chevron_right


Output:

After clicking “press” button, the following is shown:
Output:

Example 2:
In the following example, “click” event is attached with given “p” and another button, using this method.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html
       
  <head>
    <script src
    </script
    <script
        $(document).ready(function() { 
              
            $("#pressbutton").live("click", function() { 
                $("p").slideToggle(); 
            }); 
            $("#insertbutton").click(function() { 
                $("<p>Inserted Element</p>").insertAfter( 
                  "#insertbutton"); 
            }); 
        }); 
    </script
    </head>
    <body
    <p>Geeks for Geeks</p
    
    <button id="pressbutton">Press to toggle</button
    <br
    <br
       
    <button id="insertbutton">Click to insert an element</button
    
</body
    
</html

chevron_right


Output :

Example 3 :
In the following example, “click” event is attached with class “div”, using this method.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html>
<head>
<title>jQuery live() method</title>
<script src =
   <script>
     
   $(document).ready(function() {
  
     $('div').live('click', function( event ){
         alert('GeeksforGeeks');
     });
  
   });
  
   </script>
   <style>
      .div{
        width: 50px; 
            height: 50px; 
            margin: 10px; 
            float: left; 
            border: 2px solid black;        
      }
  </style>
</head>
<body>
   <h1 style="color:green">GeeksforGeeks</h1
   <p>Click on any square to see the output:</p>
   <div class="div" style="background-color:#99f;"></div>
   <div class="div" style="background-color:#8f8;"></div>
   <div class="div" style="background-color:orange;"></div>
</body>
</html>

chevron_right


Output:

Note: This function was deprecated in jQuery 1.7 and finally removed in jQuery 1.9 for some of its loopholes.The function was rewritten which is commonly known as jQuery on() which is preferred for implementation.



Disadvantages of using jQuery live():
Let us look into some of the disadvantages of jQuery .live() function, for which it was deprecated and removed.

  1. As the event trigger is being delegated up to the root of the document, the use of event.stopPropagation()
    holds no meaning.
  2. Before the function handlers are executed, the function has to traverse all the way to the root of the
    document.
  3. So performance and flexibility are affected in case of large DOM and also time
    consuming.

  4. Use of jQuery live() does not support chaining.
  5. jQuery .on() :
    This jQuery function attaches one or more function handlers which match the current selector along with all child elements. The present selectors must exist on the page at the time of code calling the jQuery on(). This function was introduced in jQuery 1.7 and above, in order to simplify and merge all the previous event handlers namely live(), bind(), delegate() into one consistent function.

    Syntax :

      $(selector).on(events, childSelector, data, function handler);
    

    or

     $( document ).on( events, selector, data, function handler ); 
    
    • events : One or many events separated by space.
    • selector : Selector or child selector which triggers the event.
    • data : Data to be passed to the function handler.
    • function handler : A function which is executed on that event trigger.

    Code snippet:

    $('#parentId').on('click', '#childId', function() {
        // Code to be written
    });
    

    Note: The function handler is called every time whenever an event occurs on the selected elements.
    The events can occur on the element from the inner child element.

    Advantages of using jQuery on() :

    Let us look into some of the advantages of jQuery .on, as it is used on top of jQuery live()

    1. jQuery .on() function is the actual replacement for all event binding functions like live(), bind() and
      delegate() which gives lot of simplicity and consistency to the code.
    2. jQuery.on() function can attach event handler to the parent object which is much closer to the actual object
      which effectively improve performance.
    3. This function works well with both current and future elements.
    4. It is a good practice to use jQuery on() even for simple static elements.
    5. The event handlers are executed from innermost to outermost elements.

    Code snippets :



    $("#container a").on("click", function () {
    // some response code to the event
      alert("GeeksforGeeks.");
     });
    
    $(document).on('click', '.selector', function() {
      /* some response code to the event */ 
      alert("GeeksforGeeks");
    });
    
    $("#dataTable tbody").on("click", "tr", function(event){
      alert("GeeksforGeeks");
    })
    

    In the above example, jQuery is binding the “click” event to the tbody of the dataTable.
    If the child element is clicked, the event will reach the tbody because of event bubbling upwards.

    Code snippet for event handler:

    function print_message() {
      alert( "GeeksforGeeks" );
    }
    $( "button" ).on( "click", print_message );
    

    Note : In short jQuery on() represents a streamlined way of attaching event handlers to elements.
    Example 1 :
    This example shows, “click” event is attached to “div” square using on() method.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <html>
      
       <head>
          <title>jQuery on() method</title>
          <script src =
             
          <script>
             $(document).ready(function() {
                $('div').on('click', function( event ){
                   alert('GeeksforGeeks!');
                });
             });
          </script>
             
          <style>
             .div {
                width: 50px; 
                height: 50px; 
                margin: 10px; 
                float: left; 
                border: 2px solid black; 
             }
          </style>
       </head>
         
       <body>
          <h1 style="color:green">GeeksforGeeks</h1
          <p>Click on any square to see the output:</p>
             
          <div class = "div" style = "background-color:#99f;"></div>
          <div class = "div" style = "background-color:#8f8;"></div>
          <div class = "div" style = "background-color:orange;"></div>
             
       </body>
    </html>

    chevron_right

    
    

    Output :

    Example 2:
    This example shows, “click” event is attached to “li” using on() method.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!Doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>on demo</title>
      <style>
      li {
        width:200px;
        background: yellow;
        cursor: pointer;
        padding: 5px;
      }
      li.hover {
        background: #ccc;
      }
       
      </style>
      <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
    </head>
    <body>
      <h1 style="color:green">GeeksforGeeks</h1
      <ul>
    <li class="active">Click me!</li>
    </ul>
    <span></span>
       
    <script>
    var count = 0;
      
    $( "body" ).on( "click", "li", function() {
      $( this ).after( "<li>Paragraph number : " + (++count) + "</li>" );
    });
    </script>
       
    </body>
    </html>

    chevron_right

    
    

    Output:

    Reasons for deprecation of jQuery live():

    1. Its a bad programming practice to apply all .live() event handlers on the whole document object.
    2. On very large documents, it was giving poor performance and memory utilization along with slow response time.
    3. As the events handlers are attached to the document element, it was throwing unexpected results reducing efficiency.

    Turning live() into on():
    Turning live() into on() needs event delegation.
    The jQuery on() performs better because it binds the event handler directly to the element instead to document root.
    jQuery attaches the event handler to the closest ancestor element and then allows it to bubble up from the child element. Initially jQuery live() was used for attaching function handlers to elements that are presently not in the document and can be dynamically generated.
    Some of the delegations are as follows :

     $('#container a').live('click', function(e) {
      e.preventDefault();
      alert('Anchor element is  clicked');
    });
     

    After turning live() into on(), the code is written as follows :

     $('#container').on('click', 'a', function(e) {
       e.preventDefault();
       alert('Anchor element is  clicked');
     });
     
     $('button').live('click', execute);
     function excute() {
        // code for execution
     }
     

    After turning live() into on(), the above code is written as follows :

      $(document).on('click', 'button', execute);
      function execute() {
        // code for execution
      }
     

    In the above example, jQuery on() is called on the document.
    But performance is better if some closer element to the selector is chosen instead of the document.

     $( "#id" ).live( "click", function() {
       alert("GeeksforGeeks live event .");
     });
     

    After turning live() into on(), the above code is written as follows :

      $( "#id" ).on( "click", function() {
        alert("GeeksforGeeks on event.");
      });
     



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.