Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if element has focused child using javascript?

I'm trying to remove all jQuery from my code. Until now I used

if ($(selector).find(':focus').length === 0) {     // focus is outside of my element } else {     // focus is inside my element } 

to distinguish wether the focus is inside of one of my elements. Can you show me a jQuery-free way of doing it?

like image 962
Marc Gerrit Langer Avatar asked Nov 19 '18 07:11

Marc Gerrit Langer


People also ask

How do you check if an element is focused in JS?

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 you know if input is focused?

To check if an input field has focus with JavaScript, we can use the document. activeElement property to get the element in focus. to add an input. to check if the input element is focused.

How do you know if an element is focused in HTML?

In HTML document, the document. hasfocus() the method is used for indicating whether an element or document has the focus or not. The function returns a true value if the element is focused otherwise false is returned. This method can be used to determine whether the active element is currently in focus.

When focus () method is used in JavaScript?

JavaScript | Focus() JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc.


2 Answers

You can use Node.contains native DOM method for this.

el.contains(document.activeElement); 

will check if activeElement is a descendant of el. If you have multiple elements to check, you can use a some function to iterate.

like image 89
Northern Avatar answered Sep 27 '22 20:09

Northern


It is possible with Element's matches() method and with a simple selector string as follows:

let hasFocused = elem.matches(':focus-within:not(:focus)'); let focusedOrHasFocused = elem.matches(':focus-within'); 
like image 44
Nagy Zoltán Avatar answered Sep 27 '22 20:09

Nagy Zoltán