zero01alpha zero01alpha - 3 months ago 9
CSS Question

jQuery addClass() method adds class, but does not change css style

I am using the jQuery

addClass()
function to make the background color of a text input field red to signify an error. Here is my code

javascript

$("#id").delegate("input:text", "keyup change", function(e) {
val = $(this).val();
if (condition) {
$(this).addClass("error"); // This doesn't work
//$(this).css("background-color", "#ff8080"); // This Works

} else {
$(this).removeClass("error"); // This doesn't work
//$(this).css("background-color", ""); // This Works

}
});


css

.error {
background-color: #ff8080;
}


I inspect the element and it does indeed add and remove the error class, but it does not actually change the color like it should. If I use the
css()
method to change the color, then it works just fine, but I would like to avoid that.

Answer

This will most likely be a case of the priority of the CSS stylings added.

Out of the two of these, the first adds a new class. A class will have a priority within all of the classes added to the element, so if another class is added after this then that background color will override the error class.

The second option adds an inline style to the element, which takes priority over all of the classes added, and so will change the colour.

$(this).addClass("error"); // This adds a class element which can be overwritten
//$(this).css("background-color", "#ff8080"); // This adds an inline style.

Try:

.error {
    background-color: #ff8080 !important;
}

Or find out which class is overwriting the error class and then change that background colour.

Comments