Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Onclick function

hi,

I would like to do a simple task of creating a button and changing its color when clicked.

Function takeTurn(player)
{
     if player = "player1"
     {
           document.getElementById("btn1").bgColor=:#ffffff;
     }
}

this is my javascript code and,

<button type="button" class="button" id="btn1" onclick="playerTurn('player1');"></button>

is the code in the HTML.

I reference the js file just before the </body> tag but nothing is happening and I am at a loss.

I feel I am using the incorrect syntax but I cannot find where the problem is, please help.

Regards.

2 Answers

Hi Edward,

You have a couple of problems with your code which are the following.

  1. you don't have any parentheses around your IF statement
  2. your IF statement should have a double equals comparator, a single equals is for assigning values
  3. you're not accessing the style object for the background color
  4. the hex color code for the property value should be encapsulated by quotes
  5. last but not least, your function name should be playerTurn

Also, as a quick note, it's always recommended you start keywords with a lowercase letter. In this case, function should start with a lowercase f. As for the code, you want the below.

function playerTurn(player)
{
  if (player == "player1")
  {
    document.getElementById("btn1").style.backgroundColor = '#ffffff';
  }
}

Any time you want to change a CSS style, we always need to set it via the style object which uses camel casing for any properties that have hyphens in them such as background-color which translates to backgroundColor in JavaScript`.

Hope that helps.

At first look... your function is named takeTurn, and in the HTML you call a function named playerTurn.

Second, change document.getElementById("btn1").bgColor=:#ffffff and use document.getElementById('btn1').style.backgroundColor="#ffffff"