datasn.io
datasn.io

Reputation: 12877

How to switch between 2 CSS colors with jQuery?

I want a string of text to change color from default to #c30 when I click a button somewhere on the page, and it changes back to default when I click the button again.

My code looks like this:

$("#button").click(function() {
    var anno = $(#text);
    if (anno.css('color') == '#c30') {
        anno.css('color', '');
    } else {
        anno.css('color', '#c30');
    }

});

But it doesn't seem to work on FF3. Works in IE though. Any idea?

Upvotes: 0

Views: 2613

Answers (3)

Chad Grant
Chad Grant

Reputation: 45422

If you use named colors, this will work.

$("#button").click(function(){
      $("#text").css('color', $("#text").css('color') == 'white' ? 'black' : 'white');    
});

Hex values do not.

This is a bad way to do it anyways, I agree with the most voted up answer here. So I have updated my answer after some research.

<style type="text/css">
     .color1 { color:#fff; }
     .color2 { color:#000; } 
</style>
<script>
    $("#button").click(function(){
          $("#text").toggleClass('color1').toggleClass('color2');
    });
</script?

<div class="color1">Text</div>

Upvotes: 0

Quentin
Quentin

Reputation: 944441

I would try to separate the presentational details as much as possible, i.e. change the classes to which the element belongs, and leave the colour information in a separate stylesheet.

$("#button").click(function() {
        $("#text").toggleClass('somethingDescriptive');
});

Upvotes: 7

Thinker
Thinker

Reputation: 14474

The color #c30 is converted to #cc3300 - that's why it is not working.

Upvotes: -1

Related Questions