Home >Web Front-end >JS Tutorial >How to Detect Input Focus in jQuery: Hover vs. Focus Events?

How to Detect Input Focus in jQuery: Hover vs. Focus Events?

Susan Sarandon
Susan SarandonOriginal
2024-11-19 18:29:02807browse

How to Detect Input Focus in jQuery: Hover vs. Focus Events?

Using jQuery to Detect Input Focus

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn