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.
Written by Jacob Rask
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#