0

I have a <form> containing two text <input>s side-by-side. When both of these inputs lose focus, I want to do some stuff (send an Ajax request to server and replace them with something else in the DOM). However if I click or tab from one of the inputs to the other, I don't want to do those things.

Setting an onBlur event handler on the <form> element works fine using my setup, but there doesn't seem to be any way to determine if the other form input is my next target. If I examine document.activeElement in my handler, it points to the <body> element (in Chrome) at that point. Only afterwards does it change to the other input.

Is there any way to reliably do what I'm asking? Solutions involving jQuery or other libraries are fine.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Inkling
  • 3,544
  • 4
  • 30
  • 44

3 Answers3

1

So it turns out that event.relatedTarget was what I was looking for - this will return the DOM node receiving focus on a blur event, so it's just a matter of setting a conditional to see if it matches the other field.

However, while this works great in Chrome, relatedTarget currently isn't implemented properly in other browsers. Apparently there's a couple of workarounds:

  • In IE11, document.activeElement does actually get set to the receiving element at the time the event fires, so you can use that.

  • In Firefox, apparently event.explicitOriginalTarget can be used instead.

Inkling
  • 3,544
  • 4
  • 30
  • 44
0

Try ..

Set a global variable that stores what you last blurred from. Call it x.

Set a blur event on all elements, and set x to the last element you blurred from.

Set a focus event on all elements, and if x is not one of your two elements, then run your script.

philz
  • 1,012
  • 6
  • 11
0

Give to them both ids, like this:

<input id="id1" />
<input id="id2" />

Then, with jQuery, you can call blur() nested with the two ids.

$('#id1').blur(function(){
  $('#id2').blur(function(){
    //do your thing    
  });
});
guiguetz
  • 1
  • 2