Jquery multiple event handlers

I defined event handlers according to their class names in the last project I'm working on.

for ex. all elements with the class name "foo" must respond in a certain way to the change event. and all elements with the class name "bar" must respond in some other way.

Now some of my elements fall under both classes, i.e. class = "foo bar" and they should respond in both directions. Right now, only one of the event handler functions is called.

How to make both answers execute at the same time.

+8
javascript jquery event-handling events
source share
2 answers

It depends on how you bind the events. If you bind them through jQuery and don’t rewrite the handlers through x.onchange = function() { ... } , all related event handlers will be executed. This is because jQuery queues event handlers instead of overwriting previous bindings.

Check fiddle to see some triggered events:
and

Check fiddle to see how event handlers are rewritten, forcing only the last handler

+12
source share

What you want is a variant of the behavior pattern.

It allows you to automatically handle events for elements with specified classes or other attributes.

The usual implementation is to listen for events in the "document" and then, event.target, determine the action.

For example: fiddle ( http://jsfiddle.net/PRkAr/ )

 $(document).on('click change', '.foo.bar', function(e) { var classes = this.className.split(/\s+/); $.each(classes, function(i, cls) { handle(e, this, cls); }) }) function handle(e, elem, cls) { // example: Event type click on elem DIV with class foo alert("Event type " + e.type + " on elem " + elem.tagName + " with class " + cls); } 

Here, the handle function handles all events on elements with the classes you have selected. If you want to add other events or classes, just add them to the "on" list.

+5
source share

All Articles