Many DOM elements are focusable: divs with tabIndex, input elements, etc. Is there any simple way to check whether an element is focusable than checking a zillion of different cases? Is there a jQuery method for this?
Elements of the following type are focusable if they are not disabled: input , select , textarea , button , and object . Anchors are focusable if they have an href or tabindex attribute. area elements are focusable if they are inside a named map, have an href attribute, and there is a visible image using the map.
Today's browsers define focus() on HTMLElement, but an element won't actually take focus unless it's one of: HTMLAnchorElement/HTMLAreaElement with an href.
Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.
getElementById is the fastest.
Answer "translated" from here: Which HTML elements can receive focus?
<a>
or <area>
with href
tabindex
Additionaly, I believe that hidden elements can't get focus also.
Assuming that conditions, the following function may help you (assuming it'll always receive an jQuery element):
function canFocus( $el ) {
if ( $el.is( ":hidden" ) || $el.is( ":disabled" ) ) {
return false;
}
var tabIndex = +$el.attr( "tabindex" );
tabIndex = isNaN( tabIndex ) ? -1 : tabIndex;
return $el.is( ":input, a[href], area[href], iframe" ) || tabIndex > -1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With