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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With