Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


I'm fairly new to JavaScript. I just made this simple script:

[HTML code]

<html>
<body>

<script src="externalscript.js"></script>

<p id="text">This text will change style</p><br>
<button type="button" onclick="changeStyle()">Click me</button>
</body>
</html>

[JS code]

function changeStyle() {

status = 1;
x = document.GetElementById("text");

if(status==1) {
    x.style.color = 'blue';
    status = 2;
}

if(status==2) {
    x.style.color = 'red';
    status = 3;
}

if(status==3) {
    x.style.color = 'yellow';
    status = 1;
}

}

I want it to change the text to a different style each time the button is clicked. However, this is not working. Could anyone explain a way to do this correctly?

like image 377
YSbakker Avatar asked Jan 26 '14 11:01

YSbakker


1 Answers

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.

like image 197
mitchazj Avatar answered Oct 24 '22 00:10

mitchazj