Home > Back-end >  Why document.activeElement displaying previous focused element
Why document.activeElement displaying previous focused element

Time:10-29

I have added an keydown event listener to get currently focused DOM Element but unfortunately when focusing through tab, I am getting previously focused/active element (the element before the currently focused element if it makes sense) in console.log()

document.addEventListener('keydown', (event) => {
  switch (event.key) {
    case 'Tab':
      console.log(document.activeElement)

      break
  }
})
<button> Button </button>
<a href="#"> Anchor </a>

Any Idea why this happening?? Try pressing Tab after clicking inside the snippet iframe

CodePudding user response:

keydown is triggered on the previous element. Suppose you are on body and try to get focus to the button next, the activeElement for keydown will be body right.

You can use keyup to solve this:

document.addEventListener('keyup', (event) => {
  switch (event.key) {
    case 'Tab':
      console.log(document.activeElement)

      break
  }
})
<button> Button </button>
<a href="#"> Anchor </a>

  • Related