on function
$("selector").on("click", function(event){
//code to be executed
});
bind function
$("selector").bind("click", function(event){
//code to be executed
});
When to use on function and bind function especially?
on function
$("selector").on("click", function(event){
//code to be executed
});
bind function
$("selector").bind("click", function(event){
//code to be executed
});
When to use on function and bind function especially?
From the docs:
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
bind only works if the element exists, on will bind it to all elements matching the selector. Docs.
$(document).on("click","selector", function(event){
//code applies to all elements matching the selector.
});
both attaches event handlers to a document... bind
attaches event handler directly to the elements (which does not delegates).. so binding does not work for dynamically added element where as on
does... it uses event delegation.
with the codes you have got.. there is no difference between on
and bind
here..both does the same thing (attaches click handler to the selected element)
as to When to use on function and bind function especially?
simple answer would be,
if you are using jquery 1.7+ . use
on()
, if your element is added dynamically use.on()
.