Choose a location:
posted 2/9/2011 by Raghav Khunger
Today a person asked a question on the forums regarding the difference between .live("click", function () and .click(function () . I decided to write a quick blog on this:
http://api.jquery.com/live/.live :- Description: Attach a handler to the event for all elements which match the current selector, now and in the future.http://api.jquery.com/click/.click:- Description: Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
.live -Works for new and old elements. New elements you can think of the elements which you add via (client side code) in DOM after the page has been rendered.
.click- It attach the events to elements that exist or match the selector at the time when the call is made. Any elements which are created after that or the selector(on the basis of which the control was selected) is changed then the click event will not fire.
.live- It works for existing and future matching elements. However, it is limited to the following events: click, dblclick mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup.
On the basis of above :This will work:
<a class="FooClass">My Link</a> <script type="text/javascript"> $('a.FooClass').click(function() { alert('Click!'); }); </script>
This won't work:
<script type="text/javascript"> $('a.FooClass').click(function() { alert('Click!'); }); </script> <a class="FooClass">My Link</a>
This will work:
<a class="FooClass">My Link</a> <script type="text/javascript"> $('a.FooClass').live('click', function() { alert('Click!'); }); </script>
This will work too:
<script type="text/javascript"> $('a.FooClass').live('click', function() { alert('Click!'); }); </script> <a class="FooClass">My Link</a>
Hope it helps!
Very nice.
I'm writing blog on difference between jQuery Live and jQuery Delegate functions.
I will publish it online tonight or tomorrow ;)
Hi,
That's nice tip. But there is another method in jQuery "delegate()". After some searching I found this article which is really helpful.
http://jquerybyexample.blogspot.com/2010/08/bind-vs-live-vs-delegate-function.html
Thanks.
What kind of email newsletter would you prefer to receive from CodeAsp.Net? 18