6

Is there anyway I can detect via jQuery if a select form element is active at the moment?

I created this fiddle to demonstrate the problem:

http://jsfiddle.net/E2PhT/2/

When you hover over the "Search"-Link the search form shows up. When you now click on the select-field to open the options inside and then, without choosing anything, leave the form on the right side (move the mouse past the right edge of the grey block), the select-field stays open while everything eles disappears (as it should).

Now I would like to either make the select element inactive again, so it doesn't stay open or prevent the rest of the form from disappearing as long as the select element is still open.

So either way I have to somehow detect if the select field is still open or active. Is there any way to check this state with jQuery?

Thx for help.

TimG
  • 985
  • 3
  • 14
  • 24

2 Answers2

3

You can try :focus selector:

if (!$("select").is(":focus")) {
    // ...
}

DEMO: http://jsfiddle.net/E2PhT/3/

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Of course! Why did I not think of that? Only problem is now that it stays on :focus when it is closed. But I think I can go on from here... thx! – TimG Jun 20 '12 at 16:22
  • @TimG Yes, there should be some workarounds. You are welcome! – VisioN Jun 20 '12 at 16:23
  • 14
    Even though this is an old question: when options list is closed after you've made a selection, the – yar1 Jul 02 '15 at 16:06
0

You can use a global Boolean variable like this:

var isFocused;
$(document).ready(function(){
    $('select').focus(function(){
        isFocused = true;
    }).blur(function(){
        isFocused = false;
    });
});
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
Farahmand
  • 2,731
  • 1
  • 24
  • 27
  • Update: This specific implementation is quite inefficient nowadays. Better change it to use a *delegated event handler* instead, attached to `document` (which also removes the need for a DOM ready handler as `document` always exists). – iCollect.it Ltd Jun 30 '16 at 09:52