Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to toggle text color?

I need to toggle text color from red to green and vice versa.

<div id="logoup">DEEP</div>
<button id='btn'>CLICK</button>

CSS

#logoup{
    color:red;
}
.greened{
   color:green;
}

JS

$("#btn").click(function(){
    $('#logoup').toggleClass('greened');
});

Doesn't work. Console is empty.

jsfiddle

like image 713
qadenza Avatar asked Dec 22 '25 01:12

qadenza


2 Answers

In CSS, an id's defined styles take precedence over an class's defined styles. You can simply attached the class name to the id to fix this without the the need to use !important which should only be used as a last resort:

JS Fiddle

#logoup.greened {
  color: green;
}
like image 188
Derek Story Avatar answered Dec 23 '25 14:12

Derek Story


You could use important on green, or you could control the coloring using classes, instead of applying it to the element.

Method 1: Use important! on the greened class

$("#btn").click(function() {
  $('#logoup').toggleClass('greened');
});
#logoup {
  color: red;
}
.greened {
  color: green !important;
}
<div id="logoup">DEEP</div>
<button id='btn'>CLICK</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Method 2: Don't apply color to ID, use classes

$("#btn").click(function() {
  $('#logoup').toggleClass('red green');
});
.red {
  color: red;
}
.green {
  color: green;
}
<div id="logoup" class="red">DEEP</div>
<button id='btn'>CLICK</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 45
vol7ron Avatar answered Dec 23 '25 16:12

vol7ron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!