Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery 1.4.2: .is(":focus") gives syntax error

Assume there is a document with a single input. What I'm trying to do is as simple as this:

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

I would expect the above code to return true. Instead, firebug logs an error:

Syntax error, unrecognized expression: Syntax error, unrecognized expression: focus

What am I missing here? I assumed that the syntax used with is() is identical to $(), or I can't do that?

How would you recommend to check for a focused input if this is unfixable instead?

EDIT:

As of jquery 1.6, the :focus selector is part of jquery core: http://api.jquery.com/focus-selector/
If you need it, just upgrade.

like image 789
Razor Avatar asked Sep 01 '26 11:09

Razor


2 Answers

You can test if it's the active (focused) element bu using document.activeElement like this:

if($("input")[0] == document.activeElement) {
  //first input is focused
}

You can give it a try here. Note though that most of the time your actions are triggered on another element, so if say you clicked a button then it would have focus and now be the active element, so you couldn't check this with a button check, because the element's already changed by the time your event fired, in most cases.

like image 92
Nick Craver Avatar answered Sep 04 '26 03:09

Nick Craver


$("input").focus() should suffice. As :focus is not a selector.

  $("input").focus(function () {
         //do something
    });

Edit:

$("input:focus").runFunc(); I suppose that might work. Cletus has summed up this problem well I think, its worth a look.

like image 42
Russell Dias Avatar answered Sep 04 '26 02:09

Russell Dias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!