user431806 user431806 - 24 days ago 9
jQuery Question

Switching background-color using css classes

I have a element that has its background color set to "lightGreen" by default and upon hovering, im adding a class that should overwrite the background-color to "red".

When the class gets added (and it does), its not applying the red, but sticking with the lightGreen.

Note the element has the "disabled" class by default, but in this example i have code running .removeClass("disabled") before adding "uiHighlight".

Why is it not working as intended for me ?

I have this:

#increaseImpulse, #decreaseImpulse, #undoLastAction {
border: 1px solid black;
background-color: lightGreen;
}

.uiHighlight {
background-color: red;
}

.disabled {
display: none;
}


and this

<tr id="undoLastAction" class="disabled">
<td colspan=2>
Undo last action
</td>
</tr>


and this

$("#undoLastAction")
.hover(
function(e){
$(this).addClass("uiHighlight");
},
function(e){
$(this).removeClass("uiHighlight");
}
)
.click(function(e){
console.log("undoLastAction")
});

Answer

An id selector has more specificity than a class selector - that is why it does not work. Try this:

#undoLastAction.uiHighlight {
  background-color: red;
}

Cheers!

$("#undoLastAction").hover(
    function(e) {
      $(this).addClass("uiHighlight");
    },
    function(e) {
      $(this).removeClass("uiHighlight");
    }
).click(function(e) {
    console.log("undoLastAction")
});
#increaseImpulse,
#decreaseImpulse,
#undoLastAction {
  border: 1px solid black;
  background-color: lightGreen;
}
#undoLastAction.uiHighlight {
  background-color: red;
}
.disabled {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="undoLastAction">
  <td colspan=2>
    Undo last action
  </td>
</tr>
</table>

Comments