简体   繁体   中英

Prevent blur on second element when refocusing an element from a blur event (IE8 only)

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM