Kunal Tanwar
Kunal Tanwar

Reputation: 1291

Why document.activeElement displaying previous focused element

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

Upvotes: 2

Views: 1235

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20376

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>

Upvotes: 4

Related Questions