Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check to see if any Input elements are in focus

I have a jquery script that displays a div when any key on the keyboard is pressed. I'd like to add a condition to the script that will only run the script if no other input area (textarea or texfields) are in focus on the page. That way you can actually type on the rest of the page without showing the div.

$(document).on('keydown', function (e) {
    if (!$('#test').is(':visible')) {
        //######## IF (every input is not active....) {
        if (65 <= e.keyCode && e.keyCode <= 90) {
            $(elem).fadeIn();
            $('#textarea').val('');
            $('#textarea').focus();
            $('#textarea').val(temp);
        }
    }
});

Thanks. I can give every other textarea on the page the same ID if that is necessary.

like image 311
centree Avatar asked Jan 21 '13 02:01

centree


People also ask

How do you know if an input element is focused?

hasFocus() The hasFocus() method of the Document interface returns a boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus.

How do I find out which DOM element has the focus?

Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.

How do you know if an element is focused angular?

hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.

How do you check if a window is focused?

Use the document. hasFocus() method to check if a window has focus, e.g. if (document. hasFocus()) {} . The method returns a boolean value indicating whether the document or any element in the document has focus.


2 Answers

Use jQuery's focus pseudoselector

if ( $('input:focus').length > 0 ) {  return; }

Or for your code example

if ( $('input:focus').length == 0) { ... }
like image 51
mrtsherman Avatar answered Sep 22 '22 02:09

mrtsherman


You can use jQuery's .is() and document.activeElement like this.

var targetInput = $('#myInput');

if(!targetInput.is(document.activeElement)) {
    alert('Typed while not focused on #myInput!');
}

JSFiddle

like image 38
Austin Brunkhorst Avatar answered Sep 21 '22 02:09

Austin Brunkhorst