1
votes

I have a text input on a page to which I have bound focus() and blur() events. I'm having an issue where focus and then blur are firing unexpectedly if I follow the these steps:

  1. Click on input, focus() fires. OK.
  2. Click out of window on another window, blur() fires. OK.
  3. Click back on original window, focus() and then blur() on the input both fire. PROBLEM!
$('#password').focus(function(){
    $('#passwordStrength').slideDown(500);
}).blur(function(){ 
    $('#passwordStrength').slideUp(500);
});

I really need the focus() and blur() events not to fire when the window regains focus as it causes a div to quickly appear and then disappear.

Any ideas on how to stop this?

2
When they fire 'incorrectly' what is the actual target? My suspicion is that the whole page will get a focus() event, so you should be able to trap it before it hits your text input.Mike Brockington
Thanks for your comment @MikeBrockington, it sent me on a path to a solution! Now, in my blur function, I check if the document has focus before hiding the strength box.Random Man

2 Answers

1
votes

I ended up getting around this by checking if the document has focus as part of my blur function.

$('#password').focus(function(){
    $('#passwordStrength').slideDown(500);
}).blur(function(){ 
    if (document.hasFocus()) {
        $('#passwordStrength').slideUp(500);
    }
});

This means that my strength box stays on the page when clicking away and then behaves appropriately when clicking back into the window.

Thanks to the commenters for trying to help and sending me on the right path.

0
votes

You can use window.onfocus to detect if the current tab is focused.

function focus () {
  $('#password').focus(function(){
    $('#passwordStrength').slideDown(500);
  }).blur(function(){ 
    $('#passwordStrength').slideUp(500);
  });
}
focus();
window.onfocus = function () {
    $('#password').focus();
  focus();
}

Here the fiddle