View Full Version : [newbie] getElementByID/if else - how to change a div style

12-17-2008, 10:32 PM
Hello forum
I'm new here although I'm not new to the whole webdesign thing and I have one question that shouldnt be too difficult...

here's what I want to do.

I have a red box. When i click it, I want it black then when I click it again, I want it red again.

and here's my faulty code:

function changecolour(box)
var bkg;
bkg = document.getElementById("box");
if (bkg.style.backgroundColor = "#bf0000")
{bkg.style.backgroundColor = "#000000";}
else if (bkg.style.backgroundColor = "#000000")
{bkg.style.backgroundColor = "#bf0000";}

njow, if you try it out, you'll see that my box changes to black but doesnt change back to red when clicked again.

Any help is much appreciated, as I'm trying to fully understand this GetElementById thing. Thanks!


12-18-2008, 06:03 AM
The best way is to toggle from one class-name to the other.

This ammendment might be useful:

<style type="text/css">
<script type="text/javascript">
function changecolour(box)
var bkg = document.getElementById(box);