jquery live() and bind() methods

I get asked occasionally when to use the bind() and live() jQuery event methods. bind() will bind a handler to one or more events for each matched element, at the time the call is made; whereas live() uses event delegation to bind a handler to an event for all current and ‘future’ matched elements. If you have controls that aren’t rendered dynamically, use bind(). If you have controls that are rendered dynamically, use live().
Here are two examples.

Bind

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script language="javascript" type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>      
<script language="javascript" type="text/javascript">
    $(function() {
        $("input[type=button]").bind("click", function() {
          $(this).after("<br /><input type=\"button\" value=\"Child\" />");
        });
    });
</script>
</head>
<body>
    <form>
        <input id="btnCreate" type="button" value="Create Children" />
    </form>
</body>
</html>
In the code above, when the user clicks on btnCreate, a new <button> will be created beneath it. Clicking on any of the newly created buttons will not replicate the functionality. This is where you need to implement the live() method.

Live

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title></title>
    <script language="javascript" type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
    </script>      
    <script language="javascript" type="text/javascript">
      $(function() {
        $("input[type=button]").live("click", function() {
          $(this).after("<br /><input type=\"button\" value=\"Child\" />");
        });
      });
    </script>
</head>
<body>
    <form>
        <input id="btnCreate" type="button" value="Create Children" />
    </form>
</body>
</html>
In the code above, the user can now click on any of the buttons, and a new button will be created beneath it. The only difference is I’m using the live() method.
While choosing between bind() and live(), also note that we can bind only a single event in each call to the live() method whereas bind() can accept multiple events. Also blur, focus, mouseenter, mouseleave, change, submit are not supported with the live() method. Some more differences between live() and bind() have been listed over here

Comments

  1. As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

    ReplyDelete

Post a Comment

Popular posts from this blog

ubuntu package installation

Drupal Bootstrap Database

How to fix 500 internal privoxy error