Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus on input and remove focus using Jquery

I'm tying to check if the input has focus to add color to the back ground However when I remove the mouse and focus on another input it doesn't remove the focus anymore it actually stays with the focus! how can I remove the backgound from the first one!

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

How can I check that the class test exists

I'm tying the following if statement by not working for some reason. it may be something wrong with my code that I can't spot for some reason!

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

I would approcialte it if you can test this for me or let me know what's going wrong on the above code!?

like image 601
Fabian Avatar asked Mar 07 '23 09:03

Fabian


2 Answers

You can use the .blur

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

Or you can add class to each part of the html code:

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

And use the following JQuery code to run it.

$(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");        
    });
});
like image 70
Natalie Nicholas Avatar answered Mar 10 '23 00:03

Natalie Nicholas


For better way you can use CSS:

input:focus {
    background-color: yellow;
}

but with using jquery:

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

$('input[type="text"]').blur(function() {
    $(this).css("background-color", "#fff");
});
like image 45
Elvin Mammadov Avatar answered Mar 10 '23 01:03

Elvin Mammadov