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


So far, all answers assume that you want to bind the same callback function to multiple events. If not, consider using .on()

with an event map:



$('selector').on({
    focus: function(e) {
        // do something for focus
    },
    blur: function(e) {
        // do something else entirely for blur
    },
    ...
}

      

+9


source


Try the following:

$("textbox").bind('focus blur', function() {
    // your code
});

      

For jQuery 1.7+ has bind

been replaced by on

:



$("textbox").on('focus blur', function() {
    // your code
});

      

In both cases, the specified function will run for all events listed in the first parameter.

+3


source


Use jQuery .on()

method:

$('input').on("focus blur", function () {
});

      

If you need to do event based conditional logic:

$('input').on("focus blur", function (e) {
    var whichEvent = e.type; // Will be "focus" or "blur"
});

      

+3


source


you can use

<element>.on("eventhandlers as commaseparated list",function(){})

if you can use one function for all these handlers, or

element.click(...)
       .<anotherhandler>(...)
       .<yetanother>(...)

      

if you need different functions.

.on()

is the preferred way.

0


source


// My way
var textbox = $('input');
$(textbox).on('focus blur', function(e){
  if (e.type == 'focus'){
    // do the focus stuff
  } else if (e.type == 'blur'){
    // do the blur stuff
  }
}

      

This is untested, but the principle matters

0


source


You can use the bind function in jquery:

Example:

$(textbox).bind('focus blur',function(){
  //do something
 });

      

0


source


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







All Articles