views:

445

answers:

4

I'm experience strange behaviour with jQuery while trying to attach more than one event handler to a single event.

How would I bind two different event handlers, to the same event?

$(this).focus(function(){/*...*/});
$(this).focus(function(){/*...*/}); // replaces the previous one?

What am I missing?

Update

Do you know if it affects how event data is routed? It appears that adding a second event handler causes eventObject.data property to return undefined...?


Epilogue

The problem was somehow related to the way jQuery normalizes event handling and how the eventObject data property changed depending on routing, I had a delay timer at one point which read the property at a later time when it was undefined, I solved it by simply creating a local temporary for it.

obj.inputText.bind('blur', obj, function(e) {
    var div = e.data.div;
    setTimeout(function() { div.hide(); }, 333); // works!
    // setTimeout(function() { e.data.div.hide(); }, 333); // does not work
});
+3  A: 

That does work. I just double checked with this code:

$(document).ready(function() {
  $("#FirstName").focus(function() {
    console.log("focus1");
  });

  $("#FirstName").focus(function() {
    console.log("focus2");
  });
});

And it does produce two console messages when the input field is focused.

Are you positive that both your handlers aren't running?

Dave Ward
A: 

This should theoretically work, try if all handlers are fired using:

$(this).focus( function() { alert('handler1'); });
$(this).focus( function() { alert('handler2'); });
$(this).focus();
Pim Jager
A: 

--- moved to question; ignore ---

John Leidegren
A: 

Can't you create on "master" function that calls all needed handlers?

$(this).focus( function() { function1();function2();etc..... });

Colin