This article mainly introduces the specific implementation of the focus element in JS. For more information about the user experience, see, the accessibility, availability, and functions of websites/web apps are crucial.
When our website runs well/has a good experience, users are not aware of it, but they will certainly feel it when we do not do well. An important component of application availability and accessibility is the processing of the input focus, which developers often ignore.
An example of poor processing of input focus: After clicking a link, a window is opened, but the cursor is not focused on any element in the window. Even worse: focus to an element in the modal window, but the focus will not be returned after it is closed. Ideally, a reference will be saved when the link is triggered, the cursor will be focused to the new window, And the cursor will be moved back when the window is closed.
But what if you don't know which element the input cursor is on? Through the document. activeElement attribute, we can get the focus element in the current document!
The JavaScript
It is easy to use document. activeElement to find the selected element:
The Code 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 attribute is not only available for regular input elements, including form fields or tag links, but also available for any element with the tabIndex attribute set.
The reason I like document. activeElement is that you do not need to use event listening or delegate a listener to track the element that gets the focus-you can get this attribute 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 competing conditions. All in all, I am very satisfied with it and think it is very reliable!