JRS: In article <11**********************@j33g2000cwa.googlegroups .com>
, dated Thu, 18 May 2006 12:36:46 remote, seen in
news:comp.lang.javascript, julian_m <ju***********@gmail.com> posted :
Incredibly, this function works as expected in IE (changing the
div_id's color after every click) , whereas it only changes div_id's
color once
function colorDiv(div_id)
{
if (document.getElementById(div_id).style.backgroundC olor ==
'#00cc00'){
document.getElementById(div_id).style.backgroundCo lor = '#00cccc';
}else{
document.getElementById(div_id).style.backgroundCo lor = '#00cc00';
}
}
I call the above function this way:
<div id="div_1" onclick="colorDiv('div_1'); return false;" >
<div id="div_2" onclick="colorDiv('div_2'); return false;" >
<div id="div_3" onclick="colorDiv('div_3'); return false;" >
What's wrong with that?
Your lines are too long, so your sending agent has wrapped one. Write
shorter lines, and don't use tabs in News - see FAQ 2.3.
The expression document.getElementById(div_id) is long & slow, and
should be factored out as X ; indeed, maybe X.style can be factored.
function colorDiv(div_id) { var X = document.getElementById(div_id)
if (X.style.backgroundColor == '#00cc00')
X.style.backgroundColor = '#00cccc';
else
X.style.backgroundColor = '#00cc00';
}
function colorDiv(div_id) { var X = document.getElementById(div_id)
X.style.backgroundColor =
X.style.backgroundColor == '#00cc00' ? '#00cccc' : '#00cc00' }
Then it is likely that you will have initialised to one of those
colours, in which case you might do
var A = 1 // or 0
function colorDiv(div_id) {
document.getElementById(div_id).style.backgroundCo lor =
(A = !A) ? '#00cccc' : '#00cc00' }
NOTES :
(1) I may have introduces errors in the code; that shown is merely
illustrative of concept.
(2) I have not addressed your original question; see what others have
written for that. But the final version avoids assumptions about the
format given on reading background colour.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.