How do I find out which DOM element has the focus?
document.activeElementis now part of the HTML5 working draft specification, but it might not yet be supported in some non-major/mobile/older browsers. we can fall back to
querySelector(if that is supported). It's also worth mentioning that
document.bodycode> if no element is focused - even if the browser window doesn't have focus.
- The following code will work around this issue and fall back to
querySelectorgiving a little better support.
The approach used by Joel S, but I also love the simplicity of
document.activeElement. I used jQuery and combined the two. Older browsers that don't support
document.activeElement will use
jQuery.data() to store the value of 'hasFocus'. Newer browsers will use
document.activeElement. I assume that
document.activeElement will have better performance.