I'd like to find the currently focused element in the whole document.
I tried using the :focus
pseudoclass introduced with jQuery 1.6:
$(document).find(":focus")
But $(document).find(":focus").length
always returns 0
I'd like to find the currently focused element in the whole document.
I tried using the :focus
pseudoclass introduced with jQuery 1.6:
$(document).find(":focus")
But $(document).find(":focus").length
always returns 0
2 Answers
Reset to default 14You should be able to use the activeElement
property of the document
:
var focus = $(document.activeElement);
If you look at the jQuery documentation for :focus
it makes this perfectly clear:
If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.
It's worth noting that if no element currently has focus, activeElement
will refer to the body
.
As with other pseudo-class selectors (those that begin with a ":"), it is remended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("
*
") is implied. In other words, the bare$(':focus')
is equivalent to$('*:focus')
.
If you want an alternative to $( document.activeElement )
which will retrieve the current element that has focus you can use :
$(document).delegate( "*", "focus blur", function( event ) {
var elem = $( this );
// here use elem.is( ":focus" ) which is your element that has focus
//for example :
elem.toggleClass( "focused", elem.is( ":focus" ) );
});