Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

dom

I would like to find out, in JavaScript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and how?

The reason I was looking for this:

I'm trying to make keys like the arrows and enter navigate through a table of input elements. Tab works now, but enter, and arrows do not by default it seems. I've got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions.

like image 529
Tony Peterson Avatar asked Jan 30 '09 20:01

Tony Peterson


People also ask

How do you check if DOM element is focused?

hasFocus() The hasFocus() method of the Document interface returns a boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus.


1 Answers

Use document.activeElement, it is supported in all major browsers.

Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field.

If you need to remove the activeElement you can use blur; document.activeElement.blur(). It will change the activeElement to body.

Related links:

  • activeElement Browser Compatibility
  • jQuery alternative for document.activeElement
like image 94
7 revs, 6 users 45% Avatar answered Nov 17 '22 03:11

7 revs, 6 users 45%