Focus on entering and removing focus using jQuery

I snap to check if the input has focus to add color to the back surface. However, when I delete the mouse and focus on another input, it no longer removes the focus; it actually remains with focus! how can i remove backgound from the first!

Fullname: <input type="text" name="name"><br>
Email: <input type="text" name="email">

How to check if a class test exists

I am binding the following if statement without working for some reason. it may be something wrong with my code that I cannot determine for some reason!

$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
});

I would approve it if you can check this out for me or tell me what happens with the wrong code above?

+4
source share
3 answers

You can use .blur

$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
    $("input").blur(function(){
        $(this).css("background-color", "#ffffff");
    });
});

html:

Name: <input class="name" type="text" name="fullname"><br>
Email: <input class="email" type="text" name="email">

JQuery .

$(document).ready(function(){
    $(".name").focus(function(){
        $(this).css("background-color", "#f4fcef");
        $(".email").css("background-color", "#ffffff");        
    });
    $(".email").focus(function(){
        $(this).css("background-color", "#f4fcef");
        $(".name").css("background-color", "#ffffff");        
    });
});
+6

CSS:

input:focus {
    background-color: yellow;
}

jquery:

$('input[type="text"]').focus(function() {
    $(this).css("background-color", "#cccccc");
});

$('input[type="text"]').blur(function() {
    $(this).css("background-color", "#fff");
});
+1

you can verify that if the class exists in focus, perform one action when focusing.

 $(document).ready(function(){
$("input").focus(function(){
    if($(this).hasClass("yourclassName")){
     $(this).css("background-color", "#f4fcef");
    }

}).focusout(function(){
   if($(this).hasClass("yourclassName")){
     $(this).css("background-color", "#f4fcef");//some other color.
    }
});

});
0
source

Source: https://habr.com/ru/post/1690482/


All Articles