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">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.