Is there a ‘has focus’ in JavaScript (or jQuery)?

There is no native solution but yes there is a more elegant way you can do it:

jQuery.extend(jQuery.expr[':'], {
  focus: "a == document.activeElement"
});

You’re defining a new selector. See Plugins/Authoring. Then you can do:

if ($("...").is(":focus")) {
  ...
}

or:

$("input:focus").doStuff();

Leave a Comment