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

Solution 1:

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();

Solution 2:

$('input:focus')

It's CSS. You don't need to create a "custom selector." It already exists! http://www.w3schools.com/CSS/pr_pseudo_focus.asp

Just attach whatever process you want to do to that selector, and it will weed it out if the element in question is not focused. I did this recently to keep a keyup from instantiating an email input error check when the e-mail input wasn't being used.

If all you're trying to do is check if the user has focused on anything themselves, just do this:

if($('input:focus').size() == 0){
    /* Perform your function! */
}