Home > Web Front-end > JS Tutorial > Use JS to get the focus element code_javascript skills

Use JS to get the focus element code_javascript skills

WBOY
Release: 2016-05-16 16:54:47
Original
1422 people have browsed it

For a good user experience, website/web app accessibility, usability, and functionality are crucial.
Users don’t realize when our website is running well/the experience is great, but they will definitely feel it when we don’t do a good job. An important component of an application's usability and accessibility is the handling of input focus, but it's one that developers often overlook.

An example of poor handling of input focus: opening a window after clicking a link, but not focusing the cursor on any element in the window. Or even worse: focusing on an element in the modal window, but the focus does not return after closing. Ideally, you would save a reference when the link is triggered, then focus the cursor to the new window, and move the cursor back when the window is closed.

But what if you don’t know which element the input cursor is currently on? Through the document.activeElement property we can get the focused element in the current document!

The JavaScript

It's easy to find the currently selected element using document.activeElement:

Copy the code The code is as follows:

var focusedElement = document.activeElement;

/* For example:
var triggerElement = document.activeElement;
myModal = new MyModal({
onOpen: function () {
this.container.focus();
},
onClose: function() {
triggerElement.focus();
}
});
*/

This attribute is not only available on regular input elements, including form fields or tag links, but also on any element that has the tabIndex attribute set.

What I like about document.activeElement is that you don't need to use event listeners or delegate listeners to keep track of which element has focus - you can get this property at any time. Of course you should do extensive testing before using such a feature - whether there are any bugs in cross-browser or race conditions. All in all, I'm very happy with it and find it very reliable!
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template