0

Let's say I have some code like this:

$('#mywrapper')
    .on('click', 'button', myFunction)
    .on('change', 'input', myFunction)
;

Is there a more efficient way to wire both event and selectors up to the same function?

Jason
  • 51,583
  • 38
  • 133
  • 185

2 Answers2

0

Nope, not really actually. The only real variation here is that you can pass an object to .on() that will define all your events in one go:

$("div.test").on({
  click: myFunc,
  mouseenter: myFunc
});
joeltine
  • 1,610
  • 17
  • 23
  • this only wires up one selector to a series of events. i was hoping for multiple selectors and multiple events to one callback – Jason Jan 11 '13 at 23:58
  • Theoretically, you can move multiple events and multiple selectors in one bind: `$('#something').on('click change', 'button, input', myFunc)`. The problem here is that now you've bound events to elements where it may not make sense and cause weird functionality. Like the "click" event bound to the input field e.g.. – joeltine Jan 12 '13 at 00:03
  • right. which is why i'm asking this question in the first place :) i can accept that there's no better way, i was just wondering if there was. – Jason Jan 12 '13 at 00:06
0

You can use a 'plain object' to pass both at once:

$('#mywrapper').on({
    click: myFunc,
    mouseenter: myFunc
});

jQuery .on() (example towards the bottom)

Sharlike
  • 1,789
  • 2
  • 19
  • 30
  • as i pointed out to @joeltine, this wires up one selector to multiple events, but not multiple selectors and multiple events to one callback – Jason Jan 12 '13 at 00:00