0

I'm trying to give variable color a value of either green or red, and from there give imagePath a specific src depending on the value given to color.

From there I can switch the shirt image continuously between red and green by pressing either buttons.

What actually happens is that the shirt color changes to red. After which, it doesn't change to green even if I press the green button activating the green() function.

My HTML code:

<html>
<head>
    <script src="oands.js" type="text/javascript"></script>
    <script type="text/javascript">
    var color;
    function red(){color = "red"; change()}
    function green(){color = "green"; change()}

    function change()
    {
         if(color = "red")
         {
             imagePath = 'images/red-t-shirt.png';
          }
         if(color = "green")
         {
             imagePath = 'images/green-t-shirt.png';
         }
        O("shirt").src = imagePath;
    }
    </script>
    <title></title>
</head>

<body>
    <div id="wrapper">
        <div id="content">
            <img id="shirt" name="shirt" src="images/white-t-shirt.png">
            <div class="smallbox" id="redBox" onclick="red()">
                red
            </div>

            <div class="smallbox" id="greenBox" onclick="green()">
                green
            </div>
        </div>
    </div>
</body>
</html>

The code in oands.js :

function O(obj)
{
    if (typeof obj == 'object') 
    return obj;

        else 
    return document.getElementById(obj) 
}
gideon
  • 19,329
  • 11
  • 72
  • 113
user3121403
  • 133
  • 1
  • 3
  • 11

1 Answers1

1

You should do :

 if(color == "red")
 {
   imagePath = 'images/red-t-shirt.png';
 }
 if(color == "green")
        //^^ note the logical compare operator. Double equals
 {
   imagePath = 'images/green-t-shirt.png';
 }

Also, in this line:

function red(){color = "red"; change();}
        //You're missing a semicolon ^^

To be more correct, if you know color is always going to be a string you should use ===. See this post for more details on that: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Community
  • 1
  • 1
gideon
  • 19,329
  • 11
  • 72
  • 113