Reputation: 447
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.
Upvotes: 3
Views: 13674
Reputation: 23500
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 that always work: commas instead of colons and put quotes around any hyphenated property name.
Upvotes: 1
Reputation: 159618
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.
Upvotes: 9