jQuery multibinding events

Sometimes I find myself using the same event handler for more than one event on an element. Typically I just put the function in the global name space (or perhaps privately within the scope of the ready function depending on how the mood takes me), and then I’ll refer to the function twice. But this feels a bit like duplication.

To hide my duplication, I’ve written wasted my time creating a simple plugin that gives me the ability to bind to more than one event at once.

Paul kindly pointed out that the functionality is native to jQuery – so here’s the examples.

That’ll teach me for writing code late at night! I completely overlooked that this is native functionality within jQuery: $('input').bind('keyup change', fn);

I’m leaving the post here, but have retracted the download link (and tweaked the post a bit).

Typical code

This is where I would normally need the function twice. Here’s the lame version of the code:

$('input').keyup(function () {
  var i = 255-this.value, j = this.value;
  $('body').css('background', 'rgb(' + [i,i,j].join(',') + ')');
}).change(function () {
  var i = 255-this.value, j = this.value;
  $('body').css('background', 'rgb(' + [i,i,j].join(',') + ')');
});

Which can be simplified to:

function colour() {
  var i = 255-this.value, j = this.value;
  $('body').css('background', 'rgb(' + [i,i,j].join(',') + ')');
}

$('input').keyup(colour).change(colour);

But the colour function feels redundant because it’s only required for that little bit of closure (and sure, I know for high performance apps, it’s probably better that way, but we’re just hacking right now).

Multibind handler

With multibinding, you can bind the same event handler to more than one event:

$('input').bind('keyup change', function () {
  var i = 255-this.value, j = this.value;
  $('body').css('background', 'rgb(' + [i,i,j].join(',') + ')');
});

3 Responses to “jQuery multibinding events”

  1. Good job Remy :)) Your blog is awesome, I am glad that you share your experience with us and protect us from mistakes like this :)))

  2. Great find. I was looking for this.

    You’ll want to make sure you add “input” as well, it’s an HTML5 thing that makes sure things change like they are supposed to, for example if you paste a value into a text box it won’t change unless “input” is present.

    Eg.
    $(‘input’).bind(‘keyup change input’, fn);

    Happy coding :)

  3. It’s amazing how simple some of this stuff is and how often I’ve passed information about bind and what not. I read this article and suddenly realise how I’ve been doing everything wrong and not using what’s available :)

    I guess it’s worth a mention that in jQuery 1.7 there will only be a need for .on and .off instead of .bind, .live etc

Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight