jQuery Lover
jQuery Lover

Reputation: 871

How to select an element that has focus on it with jQuery

How can you select an element that has current focus?

There is no :focus filter in jQuery, that is why we can use something like this:

$('input:focus').someFunction();

Upvotes: 64

Views: 91617

Answers (8)

user77838
user77838

Reputation:

Lifted from the examples for the current jQuery version (1.7) docs:

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

Upvotes: 4

jmanrubia
jmanrubia

Reputation: 1967

If you use JQuery, you can write a selector like this:

$.expr[':'].focus = function(a){ return (a == document.activeElement); }

You can then select the currently focused element: $(":focus")

Not only form controls can have focus. Any html element with a tabindex can be focused in modern browsers.

Upvotes: 5

Sam Shiles
Sam Shiles

Reputation: 11249

$(document.activeElement) will return the currently focused element and is faster than using the pseudo selector :focus.

Source: http://api.jquery.com/focus-selector/

Upvotes: 153

Hengjie
Hengjie

Reputation: 4674

Here is the CoffeeScript version of it. Based upon jmanrubia's code:

$.expr[':'].focus = (a) -> a is document.activeElement

You would also call it like so $(".:focus")

Upvotes: 0

Somnath Muluk
Somnath Muluk

Reputation: 57656

For checking element has focus or not.

if ($("...").is(":focus")) {
  ...
}

Upvotes: 1

BiBi
BiBi

Reputation: 1261

alert($("*:focus").attr("id"));

I use jQuery.

It will alert id of element is focusing.

I hope it useful for you.

Upvotes: 122

Mike_G
Mike_G

Reputation: 16502

Really the best way to do it is to setup a handler for the onFocus event, and then set a variable to the ID of the element that has focus.

something like this:

var id;

$(":input").focus(function () {
     id = this.id;
});

Upvotes: 33

bendewey
bendewey

Reputation: 40235

Have you tried

$.extend($.expr[':'], {
    focused: function(elem) { return elem.hasFocus; }
});

alert($('input :focused').length);

Upvotes: 5

Related Questions