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.
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.
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 .
To check whether a specific element has focus, it's simpler: var input_focused = document. activeElement === input && document. hasFocus();
Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.
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.
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; }); });
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