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.
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.
Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.
hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.
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.
Use jQuery's focus pseudoselector
if ( $('input:focus').length > 0 ) { return; }
Or for your code example
if ( $('input:focus').length == 0) { ... }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With