Sometimes, we want to make enter key press behaves like a tab key in JavaScript.
In this article, we’ll look at how to make enter key press behaves like a tab key in JavaScript.
How to make enter key press behaves like a tab key in JavaScript?
To make enter key press behaves like a tab key in JavaScript, we can listen for the keydown event.
For instance, we write
document.addEventListener("keydown", (event) => {
if (event.keyCode === 13 && event.target.nodeName === "INPUT") {
const form = event.target.form;
const index = [...form].indexOf(event.target);
form.elements[index + 1].focus();
event.preventDefault();
}
});
to listen for the keydown event on document
with addEventListener
.
In the event listener, we check if the enter key is pressed by checking if event.keyCode
is 13.
And we check if the key is pressed in an input with
event.target.nodeName === "INPUT"
If both are true
, then we get the form the input is in with event.target.form
.
Then we get the index of the input with [...form].indexOf(event.target)
.
Next, we focus on the next input with form.elements[index + 1].focus()
.
And we call preventDefault
to stop the default behavior.
Conclusion
To make enter key press behaves like a tab key in JavaScript, we can listen for the keydown event.