Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Dec 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    [newbie] getElementByID/if else - how to change a div style

    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:

    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

  • #2
    Senior Coder rangana's Avatar
    Join Date
    Feb 2008
    Location
    Cebu City, Philippines
    Posts
    1,752
    Thanks
    65
    Thanked 372 Times in 365 Posts
    The best way is to toggle from one class-name to the other.

    This ammendment might be useful:
    Code:
    <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>
    Learn how to javascript at 02geek

    The more you learn, the more you'll realize there's much more to learn
    Ray.ph


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •