Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an input field has focus in vanilla JavaScript

Using jQuery, I can test if an input field has focus like so:

if ($("...").is(":focus")) {     ... } 

How do I do that without using jQuery?

like image 1000
Simon Steinberger Avatar asked Jun 08 '15 16:06

Simon Steinberger


People also ask

How do you know if input field has focus?

HTML DOM Document hasFocus() The hasFocus() method returns a true if the document (or any element in the document) has focus. Otherwise it returns false .

How do you know element is focused or not?

To check whether a specific element has focus, it's simpler: var input_focused = document. activeElement === input && document. hasFocus();

What is focus () JavaScript?

focus() Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element. The focus can be applied either to a text, a button, etc.


1 Answers

This question was answered here: Javascript detect if input is focused

Taken from the above answer:

this === document.activeElement // where 'this' is a dom object 
like image 121
richardgirges Avatar answered Sep 23 '22 00:09

richardgirges