Is there something I can do like this (perhap via a plugin)
if ( ! $('form#contact input]').hasFocus()) {
$('form#contact input:first]').focus();
}
Basically, set focus to the first input, but only if the user has not already clicked into anything?
I know this will work too, but is there anything more elegant?
$(function() {
var focused = false;
$('form#contact input]').focus(function() {
focused = true;
});
setTimeout(function() {
if ( ! focused) {
$('form#contact input:first]').focus();
}
}, 500);
});
Frustratingly difficult to find a solution to this problem considering the solution is actually very simple:
jQuery 1.6 now has a dedicated
:focus
selector.No, there isn't.
However, you can simulate it like this:
I know this is an old question, but may be my solution will help someone :)
since this didnt worked for me:
..were "this" is returned from blur function. So i did this:
I had trouble with cletus approach, using jQuery 1.3.2 and Firefox 3.6.8, because the string
"a == document.activeElement"
was not a valid function.I fixed it defining a function for the
focus
key. In fact, all other keys defined injQuery.expr[':']
are defined as functions. Here's the code:So, now it works as expected.
However, I was experiencing some strange behaviour in Firefox 3.6.8 (maybe a bug in FF?). If I clicked on an input text while the page was rendering, and if I called
is(":focus")
on page load, I would get an error from the browser, reported by FireBug, and the script would break.To solve this, I surrounded the code with a
try...catch
block, returningfalse
on error. Use it if you want to prevent your users from experiencing the same error:$('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: