2

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?

1 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

1 Comment

@Louis?, don't foget to accept answer in order to help other people.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.