12

I have a custom jQuery plugin which binds a change event to a form element, in this case some input elements. The change event is used to indicate to some other components that a change has taken place.

This works as it should.

However, I've come across the need to bind an additional change event to the same input elements -- so that additional components can act on the event. I don't wish to replace the plugin's change, simply run an additional function afterwards.

Is there any way to bind multiple events in jQuery, or, what is the best method for accomplishing this?

Lachlan McDonald
  • 2,195
  • 2
  • 21
  • 25

2 Answers2

22

You can bind multiple handlers for the same event. Bind the second change as you normally would:

​<input type="text" id="a" />​​​​​​​​​​​​​​​

​$("#a"​).change(function() { alert("1"); });
$("#a").change(function() { alert("2"); });​

$("#a").change(); // alerts 1, then 2
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • 2
    Ah cheers. I was under the impression doing so would replace the first function. – Lachlan McDonald Apr 18 '10 at 10:15
  • Does the same logic apply to using `bind()` with an object, instead of each individual function? As I didn't have the same success using `bind()`. – Lachlan McDonald Apr 18 '10 at 14:21
  • `change` is just a shorthand to `bind`, so it should work. what problems are you having with using bind? created a little example with passing a function reference to bind - http://jsfiddle.net/B9ggj/ – Anurag Apr 18 '10 at 19:29
  • 1
    Can you make sure that a certain order is followed? – molerat Nov 09 '16 at 16:11
7

Events stack in jQuery. If you do:

<input type="button" value="Press me">

and:

$(":button").click(function() {
  alert("click");
}).click(function() {
  alert("click 2");
});

both will fire. So just bind another event to the relevant elements. It won't overwrite the first.

cletus
  • 616,129
  • 168
  • 910
  • 942