0

I've got a button that when pressed changes a variable between true and false. When true I want the test to display blue, when false I want the text to display black. I'm not sure why but the text is staying blue, despite the variable changing. Here's my code:

<div id="test1">Hello</div>
<button onclick="change()">Change</button>

<script>

var swap = true;
function change(){
    if(swap === true){
        swap = false;
    }
    else{
        swap = true;
    }

    document.getElementById('test1').innerHTML = swap;  
}

if(swap === true){
    document.getElementById("test1").style.color = "blue";
}

else if(swap === false){
    document.getElementById("test1").style.color = "black";
}
</script>
1
  • 1
    Because the code to change the text color is only executed when the page loads. You need to move the code to set the color into the change() method. Commented Mar 11, 2015 at 14:29

2 Answers 2

1

Because the style change isn't within the function, so it is called once on page load but not when the button is clicked. Try moving the if/else condition within the function.

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

Comments

0

Why not get rid of the if and else if statement and put the logic in the change() function.

JSFIDDLE DEMO

var swap = true;

function change() {
    if (swap === true) {
        swap = false;
        document.getElementById("test1").style.color = "black";
    } else {
        swap = true;
        document.getElementById("test1").style.color = "blue";
    }

    document.getElementById('test1').innerHTML = swap;
}

Comments

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.