views:

431

answers:

3

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?

A: 

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>
Chad Grant
jQuery doesn't need to "know" anything - it directly applies the color you specify to the appropriate property; therefore, short HEX values are okay to use.
J-P
Also, the computed style returned from the 'css' method will rarely return the HEX value of the colour. For example, say you apply #FFFFFF to an element; when you try retrieving it you'll get rgb(255, 255, 255) ...
J-P
@JimmyP Not always true, it does not return the computed style when using named colors for example. If you view the source of jQuery in SVN, you will see that computedStyle is the last thing taken into account. Try this out to see $(function() { $(".colorMe").css('color', 'red'); alert($(".colorMe").css('color')); } I don't change things like this anymore anyways, add/removeClass is a better way to switch styles
Chad Grant
A: 

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

Thinker
+7  A: 

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');
});
David Dorward