4
votes

I have two text boxes, both have blur events handled through jQuery. When a text box is blurred, some validation occurs and if the validation fails the text box is refocused (an awful idea, i know, but it's desired behavior in this case).

In chrome, if you focus the first text box then try to focus the second, you'll see this order of events happen:

  1. focus fired from text1
  2. blur fired from text1
  3. focus fired from text1

In IE8, however, you'll see this:

  1. LOG: focus fired from text1
  2. LOG: blur fired from text1
  3. LOG: focus fired from text1
  4. LOG: focus fired from text2
  5. LOG: blur fired from text2
  6. LOG: focus fired from text1

I need to be able to prevent the focus and blur events from firing on the second text box in the case that the first text box is being refocused.

Here is a fiddle demonstrating the issue. The behavior only happens in IE8.

Some more information: all of these event handlers are bound in separate private scopes, so the two text boxes have no way (that I know of) of interacting with each other's handler functions.

1
Could you provide steps to reproduce the issue? When I tab from the first text field, it fires blur1 focus1 focus2 but 1 doesn't get focus back (FF17).Fabrício Matté
@FabrícioMatté added to the questionjbabey
I see. I think you may want to fire the first box's validation when the second one gets focus instead of when the first one blurs. It seems to solve it for FF17 at least. jsfiddle.net/ult_combo/zeeth/1 (creates some more handler triggering which can be avoided though)Fabrício Matté
@FabrícioMatté the refocus only happens if validation on the first element failed - the second text box has no way of knowing about this, so i can't move the focus() call.jbabey
That will be slightly tricky then.. A setTimeout(function() { $('#text1').focus(); }, 0); is ugly and will fire the 2nd textbox's events but takes care of it as well.Fabrício Matté

1 Answers

0
votes

Although I don't like having a global state, it seems that you can't convince IE8 not to fire another blur event on the second textarea, so you'll have to work around it. Since the blur event on the first textarea is sent before the second one gets focused, you could:

  • check if the validation fails, and if it does, mark in a global variable that you're currently validating textarea1
  • on focus/blur, if there's another element that's being validated instead of the current one, just ignore the event and return
  • if the validation succeeds, remove the currently validating element from the global variable

It's a hack, but when dealing with buggy browsers, you have to use some hacks...