15ongm 15ongm - 5 months ago 29
jQuery Question

Why cannot override CSS background color on Bootstrap button?

What I want to happen



enter image description here

What's actually happening



enter image description here

I want to toggle the
red-background
class, so that when the mouse hovers over the
button-bullet
, it changes its
background-color
to
#FCC1C5
.

I don't want to use
.btn.button-bullet:hover
because I have some jQuery logic that disables the remove button from showing up when there is only one bullet element on screen.

For some reason, when I
toggleClass("red-background")
, nothing shows up.

I think it might be because in the CSS, I set
.btn.button-bullet
's
background-color
to
transparent
. So if that is the problem, how do I override the
background-color
in jQuery?

Code



HTML

<div class="worksheet-problems">
<div class="row">
<div class="col-lg-7">
<div class="form-group">
<div class="input-group input-group-lg worksheet-problem">
<div class="input-group-btn">
<button type="button" class="btn btn-default button-bullet"> <span class="glyphicon glyphicon-one-fine-dot" aria-hidden="true"></span> </button>
</div>
<input type="text" name="Worksheet-Problem" class="form-control" placeholder="Problem..." aria-label="Write worksheet problem here">
<div class="input-group-btn">
<button type="button" class="btn btn-default button-add" aria-label="Add"> <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> </button>
</div>
</div>
</div>
</div>
</div>
</div>


CSS

.red-background{
background-color: #FCC1C5;
}
/*get rid of Boostrap default grey for buttons*/
.btn.button-add, .btn.button-bullet{
background-color: transparent;
}


jQuery

$(document).ready(function() {
$(".worksheet-problems").on("mouseenter mouseleave", ".button-bullet", function() {
if ($(".worksheet-problems").children().length > 1) {
$(this).children(".glyphicon").toggleClass("glyphicon-one-fine-dot");
$(this).toggleClass("red-background");
$(this).children(".glyphicon").toggleClass("glyphicon-minus-sign");
}
});
});


JSFiddle

Answer

Problem: your red-background class has lower specificity than .btn.button-bullet.

Solution (add more specificity and place it after selectors with transparent background):

.btn.button-add, .btn.button-bullet {
  background-color: transparent;
}
.btn.red-background {
  background-color: #FCC1C5;
}