Reputation: 5259
Without considering the performance, I always tough the jquery object returned by $(":focus")
would be equivalent to $(document.activeElement)
.
However, if you're breaking into browser debugger and evaluate $(":focus")
, you won't get any element while $(document.activeElement)
will still return the focused element. I was thinking about some kind of observer effect issue but the same is also true if you set the focus outside the browser.
According to jquery documentation, the focus selector should "Selects element if it is currently focused". As there's no mention about the browser focus, I was wondering if this was the expected behaviour or if it should be reported as a bug.
If you want to try this behaviour, I created a JsFiddle example. You'll see text how $(":focus")
reacts when you'll focus away from the input (within the form, in the console or in an other application).
Upvotes: 1
Views: 74
Reputation: 20250
Take a look at the source for the :focus
selector:
"focus": function( elem ) {
return elem === document.activeElement
&& (!document.hasFocus || document.hasFocus())
&& !!(elem.type || elem.href || ~elem.tabIndex);
}
So in order for the element to be returned, elem
must equal the document.activeElement
, the document must have focus, and the element must have a type
, href
, or tabIndex
property.
The two are not equivalent
edit
In your fiddle when you remove focus from the input, document.activeElement
becomes the body
, and it doesn't matter whether or not the document has focus.
Upvotes: 2
Reputation: 2368
As you can see here CSS :focus Selector
The :focus selector is allowed on elements that accept keyboard events or other user inputs.
And document.activeElement
can contain any or almost any element from the page
Upvotes: 0