bonaca bonaca - 3 months ago 7
Javascript Question

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

Answer

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>