What is the difference between the following lines of code, or are they just 2 different ways to write the same thing:
$("p").click(function() { some code here });
$("p").bind("click", function(){ some other code here });
Am I over simplifying this? Because if you wanted to bind more than one event you could just chain the events, correct?
In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future.
Benefits: Simplifies initialization and saves memory: no need to add many handlers. Less code: when adding or removing elements, no need to add/remove handlers. DOM modifications: we can mass add/remove elements with innerHTML and the like.
Event binding lets you listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches. See the live example / download example for a working example containing the code snippets in this guide.
The verb bind means to secure or fasten something using rope or another kind of restraint. Unbind is the opposite (you can tell from the "reverse" prefix un-).
It also allows you to bind the same anonymous method to multiple events like:
$("p").bind("click dblclick mouseover mouseout", function(){ some other code here });
Also note that binds allows for custom events
$(elem).bind('myEvent', function(){
alert('myEvent!');
});
$(elem).trigger('myEvent'); //alerts 'myEvent!'
The first version is just a shorthand for the second one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With