I am fairly new to JavaScript and looking for some help. I have a button that I want to toggle its background color using if/else logic in JavaScript. My development environment includes ASP.net, C#, JavaScript, and VS2013 Express.
The first part of my code successfully changes the button's color to #198B07. However, when clicking again, it does not seem to trigger the "else" condition to change the color to "#2A303C". The initial state of the button is the standard gray color. Is this color getting reset on the second click, causing the initial "if" statement to be true again? It seems like once the color changes to #198B07, it remains that way for all subsequent clicks.
Can anyone identify what might be going wrong with my code?
Here is the code snippet:
JavaScript
<script>
function myFunction2() {
if (document.getElementById("test").style.background != '#198B07') {
document.getElementById("test").style.background = '#198B07';
} else {
document.getElementById("test").style.background = '#2A303C';
}
return false;
}
</script>
HTML
<button type="button" id="test" onclick="myFunction2()">Try it</button>