.bind function is used in jQuery to have an event attached to a form element. But what happens if you have the same element name (for eg: CSS name) happening more than once in a page, and that too getting added to a page dynamically? In such a situation, .live is handy. It will propagate the event to the dynamically added new elements.
Here is an example:
<div class="clickhere">click event to be added using jQuery</div>
$('.clickhere').bind('click', function() {
alert('i am clicked');
});
This will attach the click event to the div stated above and on click user gets the message "i am clicked".
Now what happens if you dynamically add few more elements to page which has the same class? Event wont be propagated if you use the bind method.
Lets say:
$('body').append('<div class="clickhere">another dynamic click button</div>');
As the bind event is added above this, the event is not propagated but see how it works if we use live.
$('.clickhere').live('click', function() {
alert('i am clicked');
});
and later on if you have any no. of new elements created dynamically with same class name, it will all have the same event handler attached.
If you want to remove the event, you can use the .die method.
Say:
$('.clickhere').die('click');
Syntax:
.live/bind (eventType, eventHandler)
.live/bind (eventType, eventData, eventHandler)
eventType - click / keydown etc
eventHandler - function to be executed
eventData - additional data for the event
No comments:
Post a Comment