I’m trying to make a “strobe light” for the heck of it in javascript and I found some code that would do it for me on the internet…but they used bgcolor and I felt that I should be proper but the code only works if I leave it bgcolor…so you know what I mean here’s the original:
<html><head>
<title>Strobe</title>
<script>
function toggleBgColor()
{
document.bgColor = document.bgColor == '#ffffff' ? '#000000' : '#ffffff';
setTimeout('toggleBgColor()', 70); //in milliseconds
}
</script>
</head>
<body onLoad='toggleBgColor();'>
</body></html>
and Here’s my changes:
<html><head>
<title>Strobe</title>
<script>
function toggleBgColor()
{
document.body.style.background-color = document.body.style.background-color == '#ffffff' ? '#000000' : '#ffffff';
setTimeout('toggleBgColor()', 70); //in milliseconds
}
</script>
</head>
<body onLoad='toggleBgColor();'>
</body></html>
I’ve also tried changing the document.body.style.background-color to document.body.style.background and document.body.style.backgroundColor …None of them work…what am I doing wrong?
document.body.style.background-coloris an invalid identifier (well, technically it’s a valid identifier [document.body.style.background], followed by an operator [-], followed by another valid identifier [color], but you know what I mean). Usedocument.body.style.backgroundColorinstead. It does work, provided other things are correct. Live exampleYou’ve said you’ve tried that. I suspect the problem is that your code is failing elsewhere. For instance, you’re comparing to
'#ffffff':The browser may not (probably won’t) report back to you in the same format you use to assign the color. That value will come back as
"white"in some browsers, and asrgb(255, 255, 255)in others, etc. So the comparison will frequently fail, even when the background color is white. You’d have to handle that complexity, parsing thergband doing lookups on color names, etc. —or maintain a flag as in my example above.Off-topic: Avoid passing strings into
setTimeout; instead, use function references directly. In your case:Note no quotes, and no
()(because they would call the function; we want to pass its reference in, not its return value).If passing arguments (you’re not there, but just for completeness), you can use a function to do that: