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?
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.
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.
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.
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.
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.
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');
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