Simon
Simon

Reputation: 17

My button doesn't change function

I was wondering why the button doesn't change to the other function where the button will turn red when clicking it a second time.

My goal is to have one button that will change function depending on whether you pressed it once

<!DOCTYPE html>
<html>
<head>
    <style>
        #hello {
           padding: 30px 60px;
           background-color: #4db8ff;
           width: 100px;
           text-align: center;
           margin-left: auto;
           margin-right: auto;
           cursor: pointer;
           color: white;
           font-family: arial;
           font-size: 20px;
        }
    </style>
</head>
<body>

<div id="hello" onclick="button()">START</div>
</body>
<script>

    var x = true;

    if(x == true) {
        function button() {
            x = false;
            alert("once");
        }
    }
    
    if(x == false) {
        function button() {
            alert("twice");
            document.getElementById("hello").style.background = "#ff3333";
        }
    }
</script>
</html>

Upvotes: 0

Views: 95

Answers (2)

Unmitigated
Unmitigated

Reputation: 89517

Your function button() is only being defined once. You can not define a function based on a condition, it will be defined as soon as its surrounding code is executed. Thus, you need to place your if statements inside the function.

<!DOCTYPE html>
<html>
<head>
    <style>
        #hello {
           padding: 30px 60px;
           background-color: #4db8ff;
           width: 100px;
           text-align: center;
           margin-left: auto;
           margin-right: auto;
           cursor: pointer;
           color: white;
           font-family: arial;
           font-size: 20px;
        }
    </style>
</head>
<body>

<div id="hello" onclick="button()">START</div>
</body>
<script>

    var x = true;
function button(){
    if(x) {
            x = false;
            alert("once");
    } else {
            alert("twice");
            document.getElementById("hello").style.background = "#ff3333";
    }
    }
</script>
</html>

Upvotes: 0

Carcigenicate
Carcigenicate

Reputation: 45826

You're conditionally creating, on page load, one of two possible function definitions. The second definition won't replace the first just because you've reassigned the boolean flag at some point.

Create a single function that checks the status of x internally:

function button() {
    if(x) { // Comparing against true is redundant
        x = false;
        alert("once");

    } else {
        alert("twice");
        document.getElementById("hello").style.background = "#ff3333";
    }
}

Upvotes: 3

Related Questions