Forum Moderators: open

Message Too Old, No Replies

background/text color switch problem

color switch

         

ineuw

3:41 pm on May 8, 2008 (gmt 0)

10+ Year Member



I am trying to switch the color of a table cell, using this simple javascript function. It works on the background color, but it doesn't change the text color as this always remains black. The initial cell background color is set by CSS, and here too the text color is unaffected. (It should be a dark blue background with white text).

What am I doing wrong? Thanks for any help given.

// CSS

table.links td
{
font: 12px Tahoma;
color: #ffffff;
font-weight: normal;
background-color: #000080;
}

// mouseover script

var changed_background = "#ffffff";
var changed_foreground = "#000080";

var normal_background = "#000080";
var normal_foreground = "#ffffff";

function change_background(tcell)
{
tcell.style.backgroundColor = changed_background;
tcell.style.color = changed_foreground;
}

function reset_background(tcell)
{
tcell.style.backgroundColor = normal_background;
tcell.style.color = normal_foreground;
}

httpwebwitch

4:04 pm on May 8, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



one tip right off the bat:

instead of changing the colors explicitly using the "style" object in code, create two CSS classes named "normal" and "changed".

CSS:


.normal{
background:#000080;
color:#fff;
}
.changed{
background:#fff;
color:#000080;
}

Then in your code, you add or remove the classes from your elements. It's much cleaner and easier to maintain, since your visual styling info stays in the CSS where it belongs.

The Mootools [mootools.net] library includes some really nifty methods for adding and removing classes. Using mootools, I'd do it this way:


function change_background(tcell){
tcell.removeClass('normal');
tcell.addClass('changed');
}
function change_background(tcell){
tcell.removeClass('changed');
tcell.addClass('normal');
}

In the absense of Mootools (or some similar JS helper library), you can do it "the long way", which involves a lot of code overhead - splitting the className property into an array using the space character as the delimiter, checking if the class name already exists in the array (comparing classes in uppercase), splicing in the new class or removing the found one, joining it all back together again and reassigning it to the element's className property. Phew.

ineuw

4:38 pm on May 8, 2008 (gmt 0)

10+ Year Member



Many thanks, httpwebwitch

Will do as recommended.