The HTML tabindex attribute is used to control whether an element can receive keyboard focus and to determine its position in the sequential keyboard navigation order.
Definition and Usage
➔ tabindex="0": This value places the element in the natural navigation order of the page and all elements have it by default.
➔ tabindex="-1": This value removes an element from the natural tab order and the user cannot reach it by pressing the Tab key.
➔ Positive values (tabindex="1", tabindex="2", etc.): The browser navigates to the positive tabindex first, then in the natural navigation order. It is recommended not to explicitly disrupt the natural tab index order.
Syntax
//In HTML
First Name:<input type="text" id="fname" name="fname" tabindex="1"><br><br>
Last Name:<input type="text" id="lname" name="lname" tabindex="3"><br><br>
Email:<input type="email" id="email" name="email" tabindex="2"><br><br>
//In Javascript
<script>
let element1 = document.querySelector("#fname");
let element2 = document.querySelector("#fname");
let element3 = document.querySelector("#fname");
element1.tabIndex = 1;
element2.tabIndex = 3;
element3.setAttribute('tabindex', '2');
</script>
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| tabindex | Global Attributes |
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML tabindex attribute Example</title>
</head>
<body>
<h3>HTML tabindex attribute Example</h3>
<p>tabindex attribute is used to control keyboard focus and keyboard navigation order.</p>
First Name:<input type="text" id="fname" name="fname" tabindex="1"><br><br>
Last Name:<input type="text" id="lname" name="lname" tabindex="3"><br><br>
Email:<input type="email" id="email" name="email" tabindex="2"><br><br>
</body>
<script>
//let element1 = document.querySelector("#fname");
//let element2 = document.querySelector("#fname");
//let element3 = document.querySelector("#fname");
//element1.tabIndex = 1;
//element2.tabIndex = 3;
//element3.setAttribute('tabindex', '2');
</script>
</html>
Click on the "Try it Now" button to see how it works.