Search code examples
javascriptdom-events

Detect click off of select element onBlur on first click. (default is second click)


I've read up on questions pertaining to detecting the state of a select menu, whether it's visible, open, or closed and the quick answer is that it's not universal and depends on what you're trying to do. My situation isn't covered by any of these answers 100%.

I need to determine when the select menu is closed, which currently works by storing a variable onblur; however, the select element does not lose focus on the first click off, but rather the second click off. Is there an event I can detect which occurs on the first click off? or make the select lose focus on the first click off rather than the second click off? Looking for pure JavaScript answers, no jQuery.

Here's some sample code demonstrating this: http://jsfiddle.net/BhnH9/1/


Solution

  • Recently there was a comment on this thread, so I decided to take another look at the issue. I don't recall quite what the original circumstances were, but I do know that I needed the select drop down to lose focus after selected an item. So lo and behold, my jQuery solution... what with me saying it had to not be jQuery :) It's been a long time, I've switched jobs, and don't know why that was a requirement.

    $('select').bind('change', function(e) {
      $(this).trigger('blur');
    });
    
    $('select').bind('blur', function(e) {
      alert('select lost focus');
    });
    

    Here's a JSFiddle: http://jsfiddle.net/7tUse/