2

In a DOM where there is multiple focus elements . The user can traverse the focus elements using tab , or traverse reverse by using shift + tab.

Listening on the focusin event how can we know whether it was triggered by TAB or Shift TAB ?

document.querySelector('#sample').addEventListener('focusin', function(){

if(isFromTAB){
 // DO traverse
}else{
  // DO different thing
}


});
vishnu sandhireddy
  • 1,148
  • 1
  • 7
  • 12
  • A [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent) has a [shiftKey](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/shiftKey) property which tells you if the shift key was pressed or not – Reyno Oct 22 '21 at 09:41
  • Does this answer your question? [what is the key code for shift+tab?](https://stackoverflow.com/questions/3044083/what-is-the-key-code-for-shifttab) – Reyno Oct 22 '21 at 09:42
  • I am not looking for keyCode, I would like to find the infromation from event happening after tab in focus event. – vishnu sandhireddy Oct 22 '21 at 11:06

1 Answers1

1

You can check the relatedTarget property of the event. For a focusin event, the relatedTarget property identifies the element that lost focus:

document.querySelector('#b').addEventListener('focusin', (e) => {
  if (e.relatedTarget?.id === 'a') {
    console.log('tab');
  } else if (e.relatedTarget?.id === 'c') {
    console.log('shift tab');
  }
});
<input id="a">
<input id="b">
<input id="c">
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156