20

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?

Konstantin Solomatov
  • 10,252
  • 8
  • 58
  • 88

1 Answers1

11

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;
}
Community
  • 1
  • 1
gustavohenke
  • 40,997
  • 14
  • 121
  • 129