Niels_
Niels_

Reputation: 86

Action on tab event without active element in Angular or Javascript

Whenever the tabkey is pressed without an active/focussed element, the first focussable element is selected (this is the general behaviour of the tab key. However, I dont want this in my application, since I want to focus on another element (not the first one).

I have tried setting event listeners for the tab key, but this only works if some element is already selected and not when no element is active.

Is there any way to listen to this 'initial tab event' when there are no active elements? In de code snippet you can see that the tab event only listens to the second tab, while it selects the first field after the first tab.

document.getElementById("form").addEventListener("keydown", function(e){
    if(e.keyCode===9){
      document.getElementById("demo").innerHTML = "Tab";

    }
  }

)
<div id="form">
    <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname"><br><br>
  <label for="lname">Last name:</label>
  <input type="text" id="lname" name="lname"><br><br>
  <input type="submit" value="Submit">
</div>

<p id="demo"></p>

Upvotes: 0

Views: 1481

Answers (1)

Damien Puaud
Damien Puaud

Reputation: 302

I would go with TabIndex:

Adding tabindex="0" to an element, you can then access it with your keyboard key. Adding tabindex="-1" does not give access to that alement keyboard-based (however, you can access it to gain focus programmatically - with .focus() or with a click for example).

So if your keyboard-based behavior doesn't work because nothing is selected, force you application to select an element on init (for example you element with a tabindex of -1):

// By using a tabindex of -1, the element won't be focusable via keyboard
// but, we can programmatically focus it.
.attr( "tabindex", "-1" )
.focus()

Upvotes: 1

Related Questions