Use the key event and Check if the key pressed is Tab (code = 9) to detect the Tab key press event in JavaScript.
Example handle the Tab keypress event in JavaScript
HTML example code.
<!DOCTYPE html>
<html>
<body>
<script>
document.addEventListener('keydown', function(event)
{
var code = event.keyCode || event.which;
if (code === 9) {
alert("Hello Tab key")
}
});
</script>
</body>
</html>
Output:
Q: How to call a function when pressing the tab key in JavaScript?
Answer: Add an event listener to the document and match the keycode with the tab keycode. If the condition is true then call function.
<!DOCTYPE html>
<html>
<body>
<script>
document.addEventListener('keydown', function(event) {
if (event.which === 9) {
hello();
}
});
function hello(){
alert("Hello function");
}
</script>
</body>
</html>
If you want to pass the field to the function, you could also add the event listener to the input itself. Then access it with event.target
Do comment if you have any doubts or suggestions on this JS event topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version