views:

526

answers:

2

Hi, I'm trying to get the hang of jQuery and I had this simple bit of code that refuses to work. Anyone got an idea of why this might not be working?

<html>
  <head>

  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $("div").live("click", divclicked);
    });

    function divclicked()
    {
      if($(this).css("background-color") == "lightblue")
        $(this).css("background-color", "red");
    }
  </script>

  <style type="text/css">

      div
      {
         background-color: lightblue;
      }

  </style>

  </head>
  <body>
    <div id="testdiv">
      this is a test
    </div>
  </body>
</html>

Thanks in advance for any inputs.

Update: The solution below to use "backgroundColor" instead of "background-color" works when the style is inline, not if you use a stylesheet.

I have updated the example to use a stylesheet.
+3  A: 

Try changing background-color to backgroundColor in your script:

if($(this).css("backgroundColor") == "lightblue")
  $(this).css("backgroundColor", "red");

The DOM tends to avoid using dashed names, as they are not valid JavaScript identifiers.


Argh! Paolo deleted his answer while i was typing up a comment on it... I hadn't realized that passing "background-color" to .css() would do anything useful, much less return the actual RGB value! In your case, the effect is the same (since your logic needs the original value preserved exactly), but still worth noting for future reference.

Also: if you use CSS classes instead of relying on being able to read and write the style directly, you'll have a much easier time - jQuery plays very nicely with CSS classes, providing easy ways to check, toggle, and modify them.

Shog9
Example: http://jsbin.com/ojeqo
Shog9
This works if the background-color style is inline. However, if the background color style is placed in a stylesheet, it does not work.
Sirpingalot
If it's in a stylesheet, you're stuck with calculated styles ( rgb(173, 216, 230) ). Better off going with class names instead.
Shog9
Correct. .css works for inline styles only. You'll need to check for applied classes if you want to use a stylesheet, as described above.
Peter J
Sorry for removing the answer, just figured yours had things covered. :)
Paolo Bergantino
Yeah, I kept getting the calculated style in rgb numbers. I guess I'm stuck with class names.
Sirpingalot
@Paolo: No worries - i'm glad i got to see it.
Shog9
A: 

The answer above is probably spot on

To avoid getting confused over difference in syntax like that in js compared to css I tend to change CSS in jquery using the JSON syntax

$(this).css({'background-color':'red', height:'200px'});

Then all you need to remember is 2 basic rules tyhat always work: commas instead of colons and put quotes aroudn any hyphenated property name.

wheresrhys