Reputation: 21
I am getting back into learning Javascript and am running into trouble with changing text color when clicking a button.
A lot of the other questions have referenced changing the color of the button itself, and the code I have does not seem to have an error.
<body>
<h1>My First Web Page</h1>
<p>Exciting stuff! This is my first web page.</p>
<button id= “color”>Change color!</button>
<script>
document.getElementById('color').onclick = changeColor; var currentColor = “red”;
function changeColor() {
if(currentColor == “red”){
document.body.style.color = “green”;
currentColor = “green”;
} else {
document.body.style.color = “red”;
currentColor = “red”;
}
return currentColor;
}
</script>
</body>
However, the line
document.getElementById('color').onclick = changeColor; var currentColor = “red”;
generates an error saying that it is an illegal token. Initially, I thought the issue had to do with not putting the code in a form. The instructional video's demonstration seemed to work fine, but I keep getting this error. Can anyone provide an idea what is going wrong?
Upvotes: 2
Views: 7482
Reputation: 48357
Your code works perfectly but you use incorrect
syntax. Change “
to "
quotation marks.
Also, you do not need to use return
statement inside the function, which represents onclick
event handler.
<body>
<h1>My First Web Page</h1>
<p>Exciting stuff! This is my first web page.</p>
<button id= "color">Change color!</button>
<script>
document.getElementById('color').onclick = changeColor;
var currentColor = "red";
function changeColor() {
if(currentColor == "red"){
document.body.style.color = "green";
currentColor = "green";
} else {
document.body.style.color = "red";
currentColor = "red";
}
}
</script>
</body>
Upvotes: 4