Using jQuery to test if an input is focus

Using jQuery to test if an input has focus - StackOverflow

jQuery 1.6+

jQuery added a :focus selector so we no longer need to add it ourselves…

1
return $('elem').is(':focus') ? true : false;

jQuery 1.5 and below

1
2
3
jQuery.expr[':'].focus = function( elem ) {
return elem === document.activeElement && (elem.type || elem.href);
};

Any version of jQuery

If you just want to figure out which element has focus, you can use $(document.activeElement); If you aren’t sure if the version will be 1.6 or lower, you can add the :focus selector if it is missing:

1
2
3
4
5
6
7
8
9
(function ($) {
var filters = $.expr[":"];
if (!filters.focus) {
filters.focus = function( elem ) {
return elem === document.activeElement && (elem.type || elem.href);
};
}
})(jQuery);
0%