Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect which form input has focus using JavaScript or jQuery

How do you detect which form input has focus using JavaScript or jQuery?

From within a function I want to be able to determine which form input has focus. I'd like to be able to do this in straight JavaScript and/or jQuery.

like image 323
Everett Toews Avatar asked Dec 10 '08 00:12

Everett Toews


People also ask

How do you check if a input is focused or not in JavaScript?

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 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();

How do I find out which DOM element has the focus?

Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.


2 Answers

document.activeElement, it's been supported in IE for a long time and the latest versions of FF and chrome support it also. If nothing has focus, it returns the document.body object.

like image 177
Juan Mendes Avatar answered Sep 23 '22 08:09

Juan Mendes


I am not sure if this is the most efficient way, but you could try:

var selectedInput = null; $(function() {     $('input, textarea, select').focus(function() {         selectedInput = this;     }).blur(function(){         selectedInput = null;     }); }); 
like image 45
Paolo Bergantino Avatar answered Sep 23 '22 08:09

Paolo Bergantino