Javascript IF statements

You may want to do different things depending on the value of a variable. An if statement is always structured like this:

if (a test) {
    
}
        

The test inside the brackets will be explained next. The principle is that if the test passes any code inside the braces (curly brackets) will be run. If the test fails nothing happens.

You already know how to find the current in-line style of an HTML element using JavaScript and how to change that style. Here you put that together with an IF statement to change the style unless it has already changed.

IF

function changeColour () {
    if (document.getElementById('colourTest').style.backgroundColor=='yellow') {
        document.getElementById('colourTest').style.backgroundColor='red'
    }
}
        

Place the above inside SCRIPT tags in the HEAD. Inside the BODY place this DIV:

<div id="colourTest" style="background-color:yellow; width:300px; height:200px;" onclick="changeColour();">
</div>       
        

The IF statement could be read as "If the named element background colour is yellow then make it red". Save the page, load it in a browser and try clicking on the DIV twice.

In more detail the IF statement is made up of these parts:

The condition can be almost anything. Often it will be whether a variable is equal to something else. That could be a number rather than text (e.g. if (myAge>40) but notice there are no quotes).

One common mistake when using IF statements is to use = instead of ==. Computers are very literal so you need to understand that = means "set this thing equal to the other" but == means "is one thing equal to the other?". If you use = in an IF statement then it will always be true (because the = makes the two sides equal).

IF ELSE

Often you want to do something different if the condition is not met:

function changeColour () {
    if (document.getElementById('colourTest').style.backgroundColor=='yellow') {
        document.getElementById('colourTest').style.backgroundColor='red';
    } else {
        document.getElementById('colourTest').style.backgroundColor='yellow';
    }
}
        

Save it, load it and click twice again.

The structure change is just to add the word ELSE and another set of curly braces. As before more than one line of JavaScript can go between the braces.

submit to reddit Delicious Tweet