Use JS to get the focus of focus element code

  • 2020-03-30 02:24:10
  • OfStack

Accessibility, availability, and functionality of a website /web app are critical to a good user experience.
Users don't realize it when our site is working well, but they definitely feel it when we're not. An important part of an application's availability and accessibility is the handling of input focus, which is often overlooked by developers.

An example of poor input focus: opening a window after clicking a link, but not focusing the cursor on any element in the window. Even worse: focus on an element in the modal window, but the focus does not return after closing. Ideally, a reference is saved when a link is triggered, the cursor is then focused on the new window, and moved back when the window closes.

But what if you don't know where the input cursor is now? With the document.activeelement attribute we can get the element that gets the focus in the current document!

The JavaScript

Using document.activeelement to find the currently selected element is easy:
 
var focusedElement = document.activeElement; 

 

This attribute is not only available on regular input elements, including form fields or < A> Tag links, and any element with the tabIndex attribute set is available.

What I like about document.activeelement is that you don't need to use event listeners or delegate listeners to track down that element to get focus -- you can always get this attribute. Of course, you should do a lot of testing before using such features -- whether there are bugs in cross-browser or race conditions. All in all, I'm happy with it and find it very reliable!

Related articles: