Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-11-19 18:29:02
Original
742 people have browsed it

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")
Copy after login

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 );
};
Copy after login

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 );
Copy after login

Alternatively, you can obtain the currently focused element with:

$(document.activeElement)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template