maniak
maniak

Reputation: 462

Testing which element has focus when one lost it

What I am trying to do is to test when an element (a SELECT) loses its focus if the focus has been transfered to another specific element (another SELECT). I want to trigger something when the focus is lost and is not on one of the two.

The problem is I test in the first select when it has lost the focus (with the blur event) if the other select has it, but the DOM is not yet updated.

Here's an exemple of what I did:

$select1.on("blur", function() {
    if($select2.is(":focus"))
    {
         // do something
    }
    else
    {
        // do something else
    }
});

$select1 and $select2 are just two variables that contain the element. I read that JQuery adds an identifier ":focus" when an element gains the focus, but the way I did it, it doesn't work.

In all cases, it goes into the else "do something else".

Upvotes: 0

Views: 266

Answers (2)

King Friday
King Friday

Reputation: 26076

Matt is right about the order of events but you can be a little more creative.

For example use a setTimeout to delay the check for blur so you know you already fired your focus. Simple.

$select1.on("blur", function() {
  window.setTimeout(function() {
    if($select2.is(":focus"))
    {
       // do something
    }
    else
    {
      // do something else
    }
  },100);
});

Try that one.

Upvotes: 2

Matt
Matt

Reputation: 75307

Because the blur event is distinctly fired before the focus of the new element is, the only thing you can do is set a variable in one event and detect it in the other.

$select1.on('blur', function (e) {
    var $that = $(this);

    setTimeout(function () {
        if (($that.data('focussed') || 0) > e.timeStamp - 5) {
            // Do something
        } else {
            // Something else
        }
    }, 1);
}); 

$select2.on('focus', function (e) {
    $select1.data('focussed', e.timeStamp);
});

See it working here; http://jsfiddle.net/uZAMm/

Upvotes: 1

Related Questions