views:

705

answers:

6

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

Update

It has came to my attention this question is similar to another, although I did not find it when looking (I never seem to!). I am refraining from deleting though as there are some good answers already.

+4  A: 

No, there isn't.

However, you can simulate it like this:

$(':input')
    .data('focused', false)
    .focus(function() { $.data(this, 'focused', true); })
    .blur(function() { $.data(this, 'focused', false); });
SLaks
Why was this downvoted?
SLaks
@Slaks all the answer's were except Vincent's (click on them). I'm +1'ing them all to counter that.
cletus
Don't know about the downvotes. Perhaps they did it when your answer was only the first line. Anyway, I gave you a +1 :)
alex
No, they didn't.
SLaks
+3  A: 

There is a plugin http://plugins.jquery.com/project/focused

Also you can check http://stackoverflow.com/questions/967096/using-jquery-to-test-if-an-input-has-focus

kasp3r
Someone ran through and downvoted (almost) all these answers for no readily apparent reason so +1 from me to counter
cletus
+1  A: 

This question is a duplicate. You can find more answers here: http://stackoverflow.com/questions/967096/using-jquery-to-test-if-an-input-has-focus

Vincent
My apologies, I never saw it.
alex
+15  A: 

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();
cletus
That's cool Cletus, never though about a custom selector!
alex
Perhaps you should submit this for newer versions of jQuery, it would be useful.
gnarf
Any idea why `jQuery.expr` uses `==` rather than `===`?
Matt Ball
+4  A: 

$('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! */
}
dclowd9901
You are wrong. jQuery, unlike CSS, does not have `:focus` or `:hover` selectors.
SLaks
Seems it does actually: http://jsfiddle.net/vnYCK/
Matt
jQuery uses CSS selectors. If it works in CSS, it works in jQ. Trust me. If you have any doubt, try the form in this page and then inspect the JS: http://www.ddrewdesign.com/contact/ Trigger code is on line 124. I haven't tried `:hover` before though, so I can't speak for that. The trick is getting the JS to do the legwork so it is able to check, so you have to put it inside of an action of some sort.
dclowd9901
It doesn't work in IE7.
SLaks
Correct. jQ only recognizes pseudoclasses that its browser recognizes.
dclowd9901
Someone ran through and downvoted (almost) all these answers for no readily apparent reason so +1 from me to counter
cletus
+7  A: 

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 in jQuery.expr[':'] are defined as functions. Here's the code:

jQuery.extend(jQuery.expr[':'], {
    focus: function(e){ return e == document.activeElement; }
});

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, returning false on error. Use it if you want to prevent your users from experiencing the same error:

jQuery.extend(jQuery.expr[':'], {
    focus: function(e){
        try{ return e == document.activeElement; }
        catch(err){ return false; }
    }
});
luiggitama