Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if currently active element is any kind of input

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.

like image 491
Primoz Rome Avatar asked Apr 07 '16 07:04

Primoz Rome


People also ask

How do you know if an element is input?

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.

How do you find the current focused element?

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.

How do you know if input is in focus?

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.

How do I check if a div has 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.


1 Answers

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;
}
like image 176
putvande Avatar answered Sep 25 '22 05:09

putvande