Last Updated: February 25, 2016
·
1.402K
· jacobrask

autofocus and activeElement

Note to self - Browser Quirks, part 1

One easy and cross-browser way to check if an element is focussed is elem === document.activeElement.

In iOS Safari, the autofocus HTML attribute does not actually do anything with the UI like it does in desktop browsers. It does however still set the document.activeElement property to the supposed autofocussed element.

So, what do we do instead? There are two ways.

elem.[moz|ms|o|webkit]MatchesSelector(':focus')

and

document.querySelector(':focus') === elem

The latter has the best browser support, and requires no prefixes.