I am trying to detect if currently active element is any kind of input field. Currently I have this:
var activeElement = document.activeElement
if (activeElement && (activeElement.tagName.toLowerCase() === 'input' ||
activeElement.tagName.toLowerCase() === 'textarea' ||
activeElement.tagName.toLowerCase() === 'select' ||
activeElement.tagName.toLowerCase() === 'button')) {
return false
}
Is there a better way to do this? I am using Vue JS, so if there is a solution with Vue API that is ok too.
Use the tagName property to check if an element is an input, e.g. if (element. tagName. toLowerCase() === 'input') {} . The tagName property returns the tag name of the element on which it was accessed.
It can be used to get the currently focused element in the document: Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.
To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.
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.
You could put all the element types you want to check in an array and check if your active Element is in it:
var activeElement = document.activeElement;
var inputs = ['input', 'select', 'button', 'textarea'];
if (activeElement && inputs.indexOf(activeElement.tagName.toLowerCase()) !== -1) {
return false;
}
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