Home > Web Front-end > JS Tutorial > How Can I Make a `` Element Focusable in JavaScript?

How Can I Make a `` Element Focusable in JavaScript?

Mary-Kate Olsen
Release: 2024-11-05 11:04:02
Original
928 people have browsed it

How Can I Make a `` Element Focusable in JavaScript?

Accessing Focus on

Elements via JavaScript

Despite the inherent focusability of certain elements (such as inputs and buttons), it is not natively possible to focus on a

element using the JavaScript focus() function.

Assigning a TabIndex

To enable focus on a

, one must assign it a tabindex attribute, which determines its position within the tab order of the page. Assigning a tabindex of 0 allows the element to be focused by the user or through JavaScript.

<code class="html"><div id="tries" tabindex="0">You have 3 tries left</div></code>
Copy after login

Setting Focus with JavaScript

After assigning the tabindex, the element can be programmatically focused using the focus() function:

<code class="javascript">document.getElementById('tries').focus();</code>
Copy after login

Considerations

  • A tabindex of -1 makes the element focusable only through JavaScript, not user interaction.
  • Focusable elements can receive keyboard events and styling upon focus (e.g., change background color).
  • Avoid assigning tabindex to elements that should not be user-focusable for accessibility concerns.

Example

The following example demonstrates focus assignment and a visual cue:

<code class="html"><style>
div:focus {
    background-color: Aqua;
}
</style>

<div>Element X (not focusable)</div>
<div tabindex="0">Element Y (user or script focusable)</div>
<div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>

<div id="test" onclick="document.getElementById('scripted').focus();">Set Focus To Element Z</div></code>
Copy after login

The above is the detailed content of How Can I Make a `` Element Focusable in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template