NightsWatch
NightsWatch

Reputation: 467

How can I make a HTML select drop-down list close on blur?

Hi I need my drop down list boxes to close once they are out of focus or if the user is hovering over any other html element other than it. How can this be achieved?

I could think of a blur event, are there any better way to handle this?

Upvotes: 0

Views: 1215

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206467

Good question, just this will work only in FF cause IE and Chrome do not recognize events targeting option elements :(

a way to (not) accomplish this is to set a timeout for the option elements that will trigger once we mouseleave it. If a new mouseenter is registered for another option in the tree, we simply clear the timeout that will otherwise .blur() any select on the page*.

LIVE DEMO

var blurSelectTimeout;

function blurSelect(){
   blurSelectTimeout = setTimeout(function(){
       $('select').blur();
   },200);
}

$('select').mouseleave(blurSelect).find('option').hover(function(e){
  if(e.type=='mouseenter') clearTimeout(blurSelectTimeout);
  else blurSelect();
});
  • Interestingly $(this).parent('select').blur(); would not work, so this is my best try.

Upvotes: 1

Related Questions