JavaScript: changing the color of text with a button, each time a button is clicked, a different style should be displayed. Does not work


I am new to JavaScript. I just made this simple script:

[HTML]

<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 him to change the text to a different style every time a button is pressed. However, this does not work. Can someone explain a way to do this correctly?

+6
source share
3 answers

it

 getElementById("text") 

not

 GetElementById("text"); 

Also, if I get what you are trying to achieve, you should put status = 1; out of function. Declare it as a global variable so that your booth changes it inside each if.

Also you should use else_if instead of if

Demo

+3
source

Try the following:

 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 immediately changes to the next if block after changing the color and thinks “it's good that it is true now” and then runs this code until the end of your current code. Using "else if" tells the browser to ignore the other "if blocks" after evaluating the first.

Hope this helps.

+4
source

You need to define the variable status=1 outside the function, otherwise each time you click the button on it it will be set to 1. You also need to change GetElementById("text"); on GetElementById("text");

 status = 1; function changeStyle() { x = document.getElementById("text"); if(status==1) { x.style.backgroundColor = 'blue'; status = 2; } else if(status==2) { x.style.backgroundColor = 'red'; status = 3; } else if(status==3) { x.style.backgroundColor = 'yellow'; status = 1; } } 
+1
source

All Articles