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

JqueryFocusCss Selectors

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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

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

Solution 2 - Jquery

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

I use jQuery.

It will alert id of element is focusing.

I hope it useful for you.

Solution 3 - Jquery

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

Solution 4 - Jquery

Have you tried

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

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

Solution 5 - Jquery

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.

Solution 6 - Jquery

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

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

Solution 7 - Jquery

For checking element has focus or not.

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

Solution 8 - Jquery

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")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjQuery LoverView Question on Stackoverflow
Solution 1 - JquerySam ShilesView Answer on Stackoverflow
Solution 2 - JqueryBiBiView Answer on Stackoverflow
Solution 3 - JqueryMike_GView Answer on Stackoverflow
Solution 4 - JquerybendeweyView Answer on Stackoverflow
Solution 5 - JqueryjmanrubiaView Answer on Stackoverflow
Solution 6 - JqueryTurboHzView Answer on Stackoverflow
Solution 7 - JquerySomnath MulukView Answer on Stackoverflow
Solution 8 - JqueryHengjieView Answer on Stackoverflow