Littlee
Littlee

Reputation: 4327

jQuery detect a <input> is focus when blur from another <input>

I have two input elements on my page and I want to detect when #aa blur, is #bb focused?


Here is what I have so far:

HTML:

<input type="text" id="aa" name="aa">
<input type="text" id="bb" name="bb">

JQuery:

$('#aa').blur(function () {
    console.log($('#bb').is(':focus'));
});


Although it works in theory,the output always returns false.

I know this is because #aa's blur event always happen before #bb's focus event.

Any help is appreciated

Upvotes: 1

Views: 951

Answers (2)

renakre
renakre

Reputation: 8291

How about using a global variable, updating its value when blur occurs on #aa, and then using it in focus event of #bb :

var i = 0;

$('#aa').blur(function () {
   i=1;
});

$('input:text').not('#aa').blur(function () {//reset when other textboxes are blurred
   i=0;
});

$('#bb').focus(function () {
   if(i==1){
       //it worked!
   }
});

Upvotes: 0

SharpEdge
SharpEdge

Reputation: 1762

Just use setTimeout() with 0 as offset to delay the call to the next cycle.

$('#aa').blur(function () {
  setTimeout(function(){
    console.log($('#bb').is(':focus'));
    },0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="aa" name="aa">
<input type="text" id="bb" name="bb">

Upvotes: 3

Related Questions