Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a dom element is focusable? [duplicate]

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?

like image 892
Konstantin Solomatov Avatar asked Aug 15 '13 20:08

Konstantin Solomatov


People also ask

How do you know if an element is focusable?

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.

Is a tag focusable?

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.

How do I find out which DOM element has the focus?

Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.

What is the fastest way to query Dom?

getElementById is the fastest.


1 Answers

Answer "translated" from here: Which HTML elements can receive focus?

  • <a> or <area> with href
  • Any form elements which aren't disabled
  • iframes
  • Any element with 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;
}
like image 60
gustavohenke Avatar answered Sep 23 '22 17:09

gustavohenke