jQuery:Selector :focus

:focus

Overview

Matches the element that currently gets the focus.

As with other pseudo-class selectors (those starting with “:”), it is recommended that focus be preceded by a token name or other choice; otherwise, generic selection ( “*”) is self-evident. In other words, $ ( ‘: focus’) equates to $ ( ‘*: focus’). If you are looking for the current focus element, $ (document.activeElement) will be retrieved without having to search the entire DOM tree.

Demo

Description:

Add a “focused” class name to those elements that have a focus method.

css code:
.focused {
    background: #abcdef;
}
html code:
<div id="content">
    <input tabIndex="1">
    <input tabIndex="2">
    <select tabIndex="3">
        <option>select menu</option>
    </select>
    <div tabIndex="4">
        a div
    </div>
</div>
jQuery code:
$( "#content" ).delegate( "*", "focus blur", function( event ) {
    var elem = $( this );
    setTimeout(function() {
       elem.toggleClass( "focused", elem.is( ":focus" ) );
    }, 0);
});

Leave a Reply

Your email address will not be published. Required fields are marked *