:focusS2C Home « Selectors « :focus
Form focus selector.
Shorthand version $(':focus')
Description
The :focus selector, selects currently focused element.
- Being a jQuery extension the
:focuspseudo selector is not part of any current CSS specification. Therefore:focuscannot take advantage of the performance boost provided by the native DOMquerySelectorAll()method. - You can get the currently focused element using
$(document.activeElement)without having to search the whole DOM tree, thus improving performance.
Syntax
| Signature | Description |
|---|---|
jQuery(':focus') | Form focus pseudo-class match |
Parameters
None.
Return
N/A.
:focus ExampleTop
Selects currently focused element..
In the example below we apply an orange background to form elements that have focus.
#main .focus{background-color:orange;}
$(function(){
$('.ourform').submit(function () { return false; }); // disable submit
$("#main").on( "focus blur", "*", function(event) {
var inFocus = $(this);
setTimeout(function() {
inFocus.toggleClass("focus", inFocus.is(":focus"));
}, 0);
});
});