
Originally Posted by
jscheuer1
rCells=document.getElementsByTagName('td');
for (i = 0; i < rCells.length; i++)
if (rCells[i].style.backgroundColor=='blue')
rCells[i].style.backgroundColor='white'
Rather than looping through all cells, which could include completely irrelevant ones, it seems far more sensible to just remember what was previously highlighted.
The first code block below is a simple example that will work for only one 'group' of elements. The second is a constructor that will create an object that can be used for highlighting. Though each object is only useful for one group like the first example, you can create multiple objects.
Code:
var highlight = (function(h, b) {
var active = null,
getRef = document.getElementById
? function(i) {return document.getElementById(i);}
: function() {return null;};
return function(o) {
var s;
if('string' == typeof o) {o = getRef(o);}
if(active) {active.style.backgroundColor = b;}
if(o && (s = o.style)) {
active = o;
s.backgroundColor = h;
}
};
})('blue', 'white');
highlight(...);
Notice that right at the end appears a function call. The first argument should be the highlight colour, and the second is the normal background colour.
Code:
var Highlighter = (function() {
var getRef = document.getElementById
? function(i) {return document.getElementById(i);}
: function() {return null;};
return function(b, h) {
var active = null;
this.highlight = function(o) {
var s;
if('string' == typeof o) {o = getRef(o);}
if(active) {active.style.backgroundColor = b;}
if(o && (s = o.style)) {
active = o;
s.backgroundColor = h;
}
};
};
})();
var o = new Highlighter('blue', 'white');
o.highlight(...);
The argument to both highlight functions is either a string that contains the id attribute value of the element to highlight, or an object reference. An example of the latter is:
HTML Code:
<td onclick="highlight(this);">
which will highlight that cell.

Originally Posted by
yfjpe
IN this table, one of the cells with start with background "blue". Therefore, how can I make this cell start as blue but change when another cell is clicked?
You can either add an id attribute to the cell, and include
Code:
#id {
background-color: colour;
}
in your style sheet. Alternatively, add a style attribute to the cell:
Code:
<td style="background-color: colour;">
I prefer the former, keeping presentation separate from content.
Mike
Bookmarks