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?
Asked
Active
Viewed 1.8k times
20
-
Does this help? http://stackoverflow.com/a/2684561/1725764 – Hashem Qolami Aug 15 '13 at 21:01
-
1@HashemQolami, that's not what he asked for. – gustavohenke Aug 15 '13 at 21:07
-
And I didn't say that is!, I just asked a question. – Hashem Qolami Aug 15 '13 at 21:11
-
1Why is this question a duplicate?! The OP _doesn't care_ about all the elements on a page that are focusable, which is what the question linked to at the top seems to answer. The OP simply wants to find out whether a given dom element can receive focus. Very different questions both. – Tejasvi Karne Jan 03 '18 at 18:31
1 Answers
11
Answer "translated" from here: Which HTML elements can receive focus?
<a>
or<area>
withhref
- 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
-
I know the list of the items which can receive focus. However, I want some ready and tested solution which covers all cases which I might not be aware about. – Konstantin Solomatov Aug 15 '13 at 21:40
-
-
6jQuery has this built in, simply use `$el.is(':focusable')` http://api.jqueryui.com/focusable-selector/ – lazd Sep 11 '14 at 19:04
-
3This is from jQuery UI, _not_ jQuery core. So why the downvote, could you explain me? – gustavohenke Sep 11 '14 at 19:34
-
-
anchors in Firefox on MacOS is not always focusable by default. I mean you can put focus on them programmatically, but not with tabbing – Anton Kononenko Feb 02 '21 at 08:37
-