Home >Web Front-end >JS Tutorial >How Can I Use JavaScript's focus() Function to Make a DIV Focusable?

How Can I Use JavaScript's focus() Function to Make a DIV Focusable?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 02:58:02891browse

How Can I Use JavaScript's focus() Function to Make a DIV Focusable?

Focusable DIVs Using JavaScript's focus() Function

While the focus() function commonly operates on form elements like input fields or buttons, it is also possible to focus on a

element. To achieve this, assigning a tabindex attribute to the div is necessary.

Assigning Tabindex

<br><div id="tries" tabindex="0">You have 3 tries left</div><br>

A tabindex of 0 places the div in the page's natural tab order. Positive values specify a specific priority within the tab order. Meanwhile, a value of -1 makes the div focusable only via script, not user input.

Example Code

<br>document.getElementById('test').onclick = function () {</p>
<p>};<br>

This script demonstrates setting focus to a div with a tabindex of -1 through a user-triggered event.

Styling Focused DIVs

To visually indicate fokus, CSS can be used:

<br>div:focus {</p>
<p>}<br>

By implementing these techniques, you can successfully focus on

elements using JavaScript's focus() function, enhancing the accessibility and user experience of your web application.

The above is the detailed content of How Can I Use JavaScript's focus() Function to Make a DIV Focusable?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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