Detecting the focused element

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Detecting the focused element

You can only focus on one element at a time. If you look at a page visually, you can tell what the focused element is by their styles. In JavaScript, you can tell what the focused element is with document.activeElement.

<a href="#">Link</a>
<button>Normal button</button>
const log = event => {
  console.log(document.activeElement)
}

const a = document.querySelector('a')
const button = document.querySelector('button')

a.addEventListener('click', log)
button.addEventListener('click', log)
Logs the active element when clicking on link and buttons

Note: Buttons do not get focus if you click on them in Firefox (Mac) or Safari. I wrote about this strange behavior in this article.

I also recommend adding this code at the top of your JavaScript file. This piece of code normalizes the differences between browsers when you click on them.

document.addEventListener('click', event => {
  if (event.target.matches('button')) {
    event.target.focus()
  }
})

Detecting the focused element automatically

Chrome devtools have a tool called Live Expression. You can use it to tell you what the focused element is at any point.

To use Live Expression, you open Chrome devtools. Click on Console. Then click on the eye icon.

Chrome Devtools Live Expression.

After clicking on the eye icon, a box with the word “Expression” will pop up.

Expression box.

Replace “Expression” with the expression you want to watch for. In this case, we set the expression to document.activeElement.

Replace Expression with document.activeElement.

The document.activeElement expression will then update automatically.

Expression for activeElement changes automatically when you focus on a new element.