Best way to bind events in jQuery
I'm looking for the best way to bind multiple events to a single element in jQuery. I am trying to avoid writing multiple statements $ (element) .bind ('event', ...) or $ (element) .event (...).
code
// old way
var textbox = $('input');
$(textbox).focus(function() { ... }
$(textbox).blur(function() { ... }
// new way
$(textbox).extend({
focus: function() {
...
},
blur: function() {
....
}
});
Unfortunately this implementation doesn't work. Does anyone have a better suggestion? Thank.
+3
source to share
7 replies
Once you've stored the jQuery object in a variable, you don't have to keep converting it to a jQuery object over and over again. You can also "bind" event bindings, as they return the original object.
Try something like this:
var $textbox = $('input'); // (Use a $ to mark variables that hold jQuery objects
$textbox
.on("focus", function() { ... })
.on("blur", function() { ... });
(Also, make sure you are using the correct event names ... I don’t know how much time I wasted looking for errors because I made up my own name for the event.)
0
source to share