Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to know if input element has focus

I am developing an application (game) which could be controlled using keyboard. The problem is that it also contains some default input elements (like login form fields). In order to prevent game reacting to keypresses when user enters their credentials, I do such a check:

if (isDef($("*:focus").attr("id")))
    return;

It works just great in almost all major browsers, but IE. In the Internet Explorer div's could also have focus on them and in almost every case some element on the page has focus on it. Thus, I want to check not if some element has focus, but some element, which can accept keyboard input has focus. In my case it's limited to textarea or input. How do I check if elements of those two types have focus?

like image 465
Denis Kulagin Avatar asked Mar 27 '12 07:03

Denis Kulagin


1 Answers

You can do this easily by using jquery's is expression.

if($("input,textarea").is(":focus")){
//input and text area has focus
}
else{
//no focus for input and textarea
}    

if you want to check only textbox focus instead of every input element, then change input with input['text']

like image 140
Vibin TV Avatar answered Oct 22 '22 08:10

Vibin TV