views:

243

answers:

5

Hi,

I am using jQuery monthly calender, in which every day is a cell, onClick in the cell, I am able to print the alert, but I also want to change the background color of the cell, on which I clicked. But I am not getting the way to call CSS using javscript. Please help me out.

Thanks, Ram

+4  A: 

In jQuery, you may use the css method to change the background-color of the cell:

// let's say this is in a loop
$(this).css('background-color', '#f00');
moff
+4  A: 

And in plain JavaScript:

var element = document.getElementById("myElement");
element.style.backgroundColor = "#fff";

Steve

Steve Harrison
A: 

To set one css property:

$("#myCalender").css("background-color","SomeColor");

To set an entire class:

$("#myCalender").addClass("DifferentBGColorClass");
SirDemon
A: 

To change the background color you could use:

document.getElementById("").style.backgroundColor = "#ffffff";
Gushiken
+3  A: 

Using JS to change the style property of any element creates a very high specificity rule which is hard to detect and remove, and less flexible when dealing with multiple style effects (say you wanted a border as well as a background, now you have twice as much work to do).

Almost invariably it is far better from a maintenance, flexibility, and separation-of-concerns point of view not to modify the style of an element directly, but to change it's class and let CSS do the work for you.

e.g I want to change to this border+background style, so I'll define a class in my CSS

.highlight
{
  border: 1px solid black;
  background: white;
}

and then I'll modify the element where I need to like so:

document.getElementById('myElementId').className += " highlight"; //note the space

Now in practice I'd actually wrap that class modifying code in a more general wrapper to protect myself from assigning the same class twice, and make removing it again easier, but in principle you can see that it would now be trivial to change the effect of "highlight" at just a single point, it allows for normal cascading, and it's much easier to detect the element has a highlight class than it is to check if it's got a background colour of FOO and a border of BAR.

It also, quite importantly adds semantic value. Self documenting code is a very good thing.

annakata