Search code examples
javascriptjqueryfocusonblur

jQuery find(':focus') not acting as expected


I'm making a widget that slides in and out of view on hover with showTracker and hideTracker functions. I want to prevent it from sliding out of view if it contains a focussed form element though, so I've got this going:

function hideTracker(){
  if($('#tracker').find(':focus').length == 0){ 
    $('#tracker').stop().hide();    
  }
}

Cool. Now it doesn't hide if the mouse happens to move out if there's a field in focus. Unfortunately, that also means that when the field does lose focus (and it's time for the widget to hide again) it just stays there. The unHover event has been and gone.

So I added this:

$('#tracker *').blur(function(){
  hideTracker();
}); 

And that works too - with one little bug that I need help with!

If the focus moves from one element within the tracker to another which is also within #tracker, the tracker hides. I figured that if($('#tracker').find(':focus').length == 0) would return false, given that the next form element has focus, but I guess it doesn't.

Is it the case that .blur() fires before the next element attains focus?

How can I get around this?


Solution

  • Thank you all for your answers. Utilising the .focus() event rather than .blur() was a clever way to look at it. Unfortunately, it does raise a couple of browser problems, and I couldn't get any of the above working very robustly.

    In the end I decided to use setTimeout(hideTracker, 100); to allow the focus() event to take place before the count of focussed elements within tracker was evaluated. Not ideal, but it's working well and the delay is fairly imperceptible.

    Thanks again.