Search code examples
jqueryfocusmouseleave

JQuery ignore mouseleave on focus


Sorry if this seems basic, I'm new to JQuery.

I have a password element on my page and I want it so that when the box is active and being typed in the box stays green, but mouseleave seems to take precedence over focus.

Here's the code for the element:

$(":password").on({
mouseenter: function(){
    $(this).css("background-color", "lightblue");
}, 

blur: function(){
    $(this).css("background-color", "white");
},
focus: function(){

    $(this).css("background-color", "#a6ff4d");

},
mouseleave: function(){
    if ($(":password").not(":focus")) {
    $(this).css("background-color", "white");
    };
},

click: function(){
    $(this).css("background-color", "chartreuse");
    } 
}); 

I have tried:

mouseleave: function(){
if ($(":password").not(":focus")) {
$(this).css("background-color", "white");
};
},

and

mouseleave: function(){
if ($("this").not(":focus")) {
$(this).css("background-color", "white");
};
},

This is the latest jquery.

Sorry, I have searched but the answers I found here didn't seem to resolve my issue.


Solution

  • You can use the jquery .is() method to check whether the password field is on :focus . So replace the code section inside onleave event with :

    if (!$(this).is(":focus")) {
        $(this).css("background-color", "white");
    }
    

    This will help you