Last Updated: February 25, 2016
·
1.693K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside