Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  39] [ 7]  / answers: 1 / hits: 69250  / 14 Years ago, wed, april 21, 2010, 12:00:00

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

More From » jquery

 Answers
24

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

[#97009] Monday, April 19, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzs

Total Points: 710
Total Questions: 113
Total Answers: 100

Location: Nepal
Member since Sat, Jul 18, 2020
4 Years ago
cruzs questions
Thu, Nov 26, 20, 00:00, 4 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
Sun, Aug 2, 20, 00:00, 4 Years ago
;