W3cubDocs

/jQuery

:focus Selector

focus selector

Description: Selects element if it is currently focused.

  • version added: 1.6jQuery( ":focus" )

As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ( "*" ) is implied. In other words, the bare $( ":focus" ) is equivalent to $( "*:focus" ). If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

Example:

Adds the focused class to whatever element has focus

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>focus demo</title>
  <style>
  .focused {
    background: #abcdef;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div id="content">
  <input tabIndex="1">
  <input tabIndex="2">
  <select tabIndex="3">
    <option>select menu</option>
  </select>
  <div tabIndex="4">
    a div
  </div>
</div>
 
<script>
$( "#content" ).delegate( "*", "focus blur", function() {
  var elem = $( this );
  setTimeout(function() {
    elem.toggleClass( "focused", elem.is( ":focus" ) );
  }, 0 );
});
</script>
 
</body>
</html>

Demo:

© The jQuery Foundation and other contributors
Licensed under the MIT License.
https://api.jquery.com/focus-selector