...

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



numtre
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!

Alex

rangana
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">
.black{
background-color:#000;
}
.red{
background-color:#bf0000;
}
</style>
<script type="text/javascript">
function changecolour(box)
{
var bkg = document.getElementById(box);
bkg.className=bkg.className=='red'?'black':'red';
}
</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum