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
}
});
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">