JavaScript: Change text color with a button, each time the button is clicked a different style should show up. Not working

Try this:

status = 1;
function changeStyle() {
//Note the lowercase first letter.
x = document.getElementById("text");

if(status==1) {
    x.style.background-color = 'blue';
    status = 2;
}
else if(status==2) {
    x.style.background-color = 'red';
    status = 3;
}
else if(status==3) {
    x.style.background-color = 'yellow';
    status = 1;
}

}

You need to use 'else if' because otherwise the browser, after changing the color, immediately moves unto the next if block, and thinks "well that's true now", and then runs that code, all the way to the end of your current code. Using 'else if' tell the browser to ignore the other 'if blocks' once the first one is evaluated.

Hope this helps.


It is

getElementById("text")

not

GetElementById("text");

Also if i get what are you trying to achieve you should put status = 1; outside the function. Declare it as a global variable so that you cab change it inside each if.

Also you have to use else_if instead of if

DEMO