Augusto
Augusto

Reputation: 19

How can I return a button to its original color

i have the following code, and I am trying to figure out how can I set the first button to white if I click it once again, same thing for the next button. So,if i clicked it once it turns red, but if I click again, it turns white. any ideas.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title> color divs </title>
        <meta name="author" content="Lee Middleton" />
        <meta name="keywords" content="CIS120/121/122" />
        <meta name="description" content="Template for x/html, CSS and JavaScript" />
        <style type="text/css">
            .container {
                border: 1px solid blue;
                border-radius: 10px;
                width: 100px;
                height: 50px;
            }
        </style>
        <script language="javascript">
            function changeColor(whichOne)
            {
                var thatOne = eval(whichOne);
                var element = document.getElementById(whichOne);
                var color = "ff";
                var stringColor;
                if (whichOne == 1)
                {
                    stringColor = "#" + color + "0000";
                    else {
                        alert('it was clicked') ;
                    }
                }




                }
                else if (whichOne== 2)
                {
                    stringColor = "#0000" + color;
                }
                element.style.backgroundColor = stringColor;
            }
        </script>

    <body>
        <div class='container' id='1' style='margin: 150px 0 0 75px; float: left;' onclick='changeColor(1);'></div>
        <div class='container' id='2' style='margin: 150px 0 0 175px; float: left;' onclick='changeColor(2);'></div>
        <div class='container' id='3' style='margin: 150px 0 0 220px; float: left;' onclick='changeColor(3);'></div>
    </body>
    </html>

Upvotes: 0

Views: 2891

Answers (6)

Oliver Ni
Oliver Ni

Reputation: 2664

You could try this:

JavaScript:

var times = 0;
function isEven(num) {
    if (num % 2 == 0) return true;
    else return false;
}
function changeColor(whichOne) {
    if (isEven(times)) {
        document.getElementById(whichOne).style.color = 'white';
    } else {
        document.getElementById(whichOne).style.color = 'red';
    }
    times++;
}

Upvotes: 0

Malk
Malk

Reputation: 11983

If all you want to do is change the appearance then you should stick to CSS classes. It is this type of inline code that can give you a headache when you go to debug it months down the road when the client wants it to turn pink instead of white.

Likewise on the inline event binding. Javascript can be invoked several ways and it can quickly become a burden keeping track of them all when there are little snippets scattered throughout your HTML.

I recommend something like the following:

HTML

<div class='container green' id='1' ></div>
<div class='container blue' id='2' ></div>
<div class='container yellow' id='3'></div>

STYLES

.container.active { background-color:white;}

JAVASCRIPT

function changeColor(el){
    var classes = el.className.split(' '), // get the current classes
        index = classes.indexOf('active'), // see if 'active' is one of them
        hasClass = index > -1;             

     if (hasClass)
         el.className = (classes.splice(index, 1), classes.join(' ')); // remove 'active' and stringify
     else
         el.className+= " active";
}

// put all calls that require the DOM to be loaded in a function
function init(){
    var divs = document.getElementsByClassName('container'),     // get all elements that need binding
        divCount = divs.length;                                  // the length of the array for looping

    // loop through array
    while(divCount--){
        // bind each element
        // using an anonymous function wrapper to pass 'this' parameter
        divs[divCount].addEventListener('click', function() { changeColor(this) }); 
    }
}

// fire the init function once the window is loaded
window.addEventListener('load', init);

http://jsfiddle.net/NpW9X/

Upvotes: 0

Tyler Rafferty
Tyler Rafferty

Reputation: 3428

Toggle the background-color or which ever attributes you want to manipulate via CSS markup from a toggle event.

Add this class to your CSS

   .container {
       background-color: #d1d1d1; 
   }
   .colorMe{
       background-color: red;
   }

Use this script

   $(document).ready(function(){
       $('.container').on("click", function(){
           $(this).toggleClass('colorMe');
       });          
   });

HTML

   <div class='container'> Button-1 </div>
   <div class='container'> Button-2 </div>
   <div class='container'> Button-3 </div>

Dont forget to link a jQuery library.

Here is a live working example: JsFiddle Example

Upvotes: 0

Fawar
Fawar

Reputation: 735

1st point

You got some {} closure problem. Your first if contains an else without an if associated with it. This same if is close {} but you close it again before the else if

2nd If I understand right you are having a function to toggle the color of the button base on it's ID.

I would write something similar to this

if(document.getElementById(whichOne).style.backgroundColor==COLOR1)
{
  document.getElementById(whichOne).style.backgroundColor = COLOR2
}
else
  documenet.getElementById(whichOne).style.backgroundColor = COLOR2

Color 1 and Color 2 and constants in the function, no need to fill the namespace.

Upvotes: 0

Coin_op
Coin_op

Reputation: 10718

As the other solution mentions you could store the previous color in a variable so you can reset it when necessary, but there is an easier way if you just want to return the element to its default colour.

Just do:

element.style.backgroundColor = '';

This just unsets the background-color part of the style attribute, allowing for the color from the css to be used.

So to toggle between default and a colour you can just do this:

element.style.backgroundColor = element.style.backgroundColor ? '' : '#' + color;

Upvotes: 3

Alex
Alex

Reputation: 11579

You need to save the previous state of the button outside this function like that

var prevColor = "#ffffff";
function changeColor(whichOne) {
prevColour = (this.prevColor=="#ffffff")?"#ff0000":"#ffffff";
// use this prevColour to change button colour
}

Upvotes: 0

Related Questions