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
Edward campbell malan van wyk
6,403 PointsOnclick 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
Chris Shaw
26,676 PointsHi Edward,
You have a couple of problems with your code which are the following.
- you don't have any parentheses around your
IFstatement - your
IFstatement should have a double equals comparator, a single equals is for assigning values - you're not accessing the style object for the background color
- the hex color code for the property value should be encapsulated by quotes
- 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.
Nicol谩s Barcel贸
17,048 PointsAt 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"