Ilja
Ilja

Reputation: 46509

How to add style to a form once someone clicks on it and remove this style when someone clicks away

Basically I have a form (id="form") with background-color: #000000; border: 1px solid #fff; I want to change it to background-color: #ffffff; border: 1px solid #000; once someone clicks on it. I tried using css:focusm but apparently it doesn't work with forms. So is there a jQuery solution to this? Also it is important that once user clicks away from the form (so when it is not in focus) it should return back to background-color: #000000; border: 1px solid #fff;

Upvotes: 1

Views: 178

Answers (2)

mhps
mhps

Reputation: 166

another option: http://jsfiddle.net/6TrGg/

$(document).ready(function(){
    $(".form").mouseover(function(){
        $(".form").removeClass("form").addClass("form2");
        $(".form2").mouseout(function(){
            $(".form2").removeClass("form2").addClass("form");
        });  
    });
});

Upvotes: 2

Craig
Craig

Reputation: 7076

I don't believe that the form element can trigger the focus event so what you could do is set the color based on blur and focus event of all elements in the form.

Markup:

<form id="myForm" method="post">
    <input type="text" />
    <input type="text" />
</form>

jQuery:

//receives focus
$("input, select").focus(function () {
    $("#myForm").css("background-color", "#fff");

    //OR
    //to swap a class with the CSS defined instead do this
    $("#myForm").addClass("your-class-name");
});

//loses focus
$("input, select").blur(function () {
    $("#myForm").css("background-color", "#000");

    //OR
    //to swap a class with the CSS defined instead do this
    $("#myForm").removeClass("your-class-name");
});

the selector input, select will select all inputs and drop downs in the page. You can further limit it by prefixing the form id as well if need be.

Upvotes: 3

Related Questions