You want to maintain a border on a form element in a div when the input within it has focus, even when the mouse moves in and out of the div. However, jQuery's hover() method is interfering with the focus() event.
jQuery 1.6
With jQuery 1.6, you can utilize the built-in :focus selector to determine input focus. Simply use:
$("..").is(":focus")
jQuery 1.5 and Below
Ben Alman's recommended method for this task is as follows:
jQuery.expr[':'].focus = function( elem ) { return elem === document.activeElement && ( elem.type || elem.href ); };
Any jQuery Version
If you need to support both versions of jQuery, you can add the :focus selector if it is missing:
(function ( $ ) { var filters = $.expr[":"]; if ( !filters.focus ) { filters.focus = function( elem ) { return elem === document.activeElement && ( elem.type || elem.href ); }; } })( jQuery );
Alternatively, you can obtain the currently focused element with:
$(document.activeElement)
The above is the detailed content of How to Detect Input Focus in jQuery: Hover vs. Focus Events?. For more information, please follow other related articles on the PHP Chinese website!