开发者

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 ev开发者_Go百科ent 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/


You can use a general click listener on the document (or some other suitable ancestor of the select) and see if the select element matches the document.activeElement. If so, then it has focus either because it just got it or an option has been selected.

However, there are other ways of selecting options than clicks, such as keyboard navigation. A click listener will not help you there.


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜