Select current item

I would like to find the element that is currently focused throughout the document. I tried using the pseudocass :focus introduced with jQuery 1.6:

 $(document).find(":focus") 

But $(document).find(":focus").length always returns 0

+4
source share
2 answers

You can use the activeElement document property:

 var focus = $(document.activeElement); 

If you look at the jQuery documentation for :focus , this makes this very clear:

If you are looking for the currently focused element, $ (document.activeElement) will retrieve it, not the whole DOM tree.

It is worth noting that if no element has focus, activeElement will refer to the body .

+11
source

As with other pseudo-class selectors (those starting with ":"), this is recommended to be preceded by: focus with the tag name or another selector; otherwise, a universal selector (" * ") is implied. In other words, bare $(':focus') equivalent to $('*:focus') .

If you need an alternative to $( document.activeElement ) that will retrieve the current element with focus, which 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" ) ); }); 
0
source

Source: https://habr.com/ru/post/1394844/


All Articles