Difference Between Live And Bind Function In jQuery

Just take a simple html page and write the code which is mentioned below in the image, and you will easily understand the difference between live and bind function of jQuery.

  1. Add a jQuery library reference in your page so that you can write jQuery code.

    Script File,
    1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>  
  2. Now add the below mentioned code in your page, and then run the page to understand the difference between live and bind.

    Script
    1. <style>  
    2.     p{border:1px solid Black;}  
    3. </style>  
    4. <p>This is a p tag</p>  
    5. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>   
    6. <script>  
    7.     $("p").bind("click", function () { alert("P tag is clicked from bind function.") });  
    8.     $("p").live("click", function () { alert("P tag is clicked from live function.") });  
    9.     $("body").append("<p>This is a future p tag.</p>")  
    10. </script>  
    Now if you see the code you can clearly see that we are just adding an event handler to a DOM element which is <p> tag.

  3. Why do we actually use these two methods, what is the working of these methods, why do we need them?

    This question must come to your mind -- these functions allow us to add event handler to any DOM object, so that we can do the changes in according to our need, for example, I want to add a click event to any p tag in my page, so how could I  do that if I don't have any on-click event in p?  So for that purpose we use these methods.

  4. What is the difference between them?

    Bind method works only for the present tags in the page, which means the already existing DOM elements, not for the tags which are getting added after this method or in the future. For example,



    Check this image, you can see we have a <p> tag with the text (This is a p tag) which means its already exists.

    If we click on p tag it will give me an alert message first ( P tag is clicked from bind function) and then ( P tag is clicked from live function), Now we added a new p tag in the body but after bind method, so basically dynamically, and this p tag will append in the body at run time.

    So in the output now we have two tags,



    Now if you click on the <p> tag which we appended at run time, it will just alert the Live function, not the bind function.

So the difference is clear:  Bind method does not work for the future tag added in the page,  where live does work for that.


Similar Articles