Jquery – Why is this jQuery code not working to alter background-color in Firefox


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?


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

    function divclicked()
      if($(this).css("background-color") == "lightblue")
        $(this).css("background-color", "red");

  <style type="text/css">

         background-color: lightblue;


    <div id="testdiv">
      this is a test

Thanks in advance for any inputs.

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.

Best Solution

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.