For a good user experience, the accessibility and availability of the website/web app, as well as the functionality are crucial.
When our website is running well/experience is good, users are not aware of it, but they will definitely feel it when we are not doing well. An important part of application availability and accessibility is the processing of input focus, but this is another point that developers often overlook.
An example of poor handling of input focus: Open a window after clicking a link, but does not focus the cursor into 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 the link is triggered, and the cursor is focused on a new window and moves the cursor back when the window closes.
But what if you don't know which element the input cursor is on now? Through the document.activeElement property we can get the element that gets focus in the current document!
The JavaScript
It is easy to use document.activeElement to find the currently selected element:
The code copy is as follows:
var focusedElement = document.activeElement;
/* For example, an example:
var triggerElement = document.activeElement;
myModal = new MyModal({
onOpen: function() {
this.container.focus();
},
onClose: function() {
triggerElement.focus();
}
});
*/
This property is not only available on regular input elements, but also includes form fields or <a> tag links, but any element with the tabIndex attribute set is available.
The reason I like document.activeElement is that you don't need to use event listening or delegate listeners to track down the element and get focus - you can get this property at any time. Of course, before using such features, you should do a lot of tests - whether there are any bugs in cross-browser or race conditions. All in all, I'm very satisfied with it and find it very reliable!