Skip to content
Advertisement

Button background color toggle

I have been trying to toggle the background-color property of a button onclick but the color only changes once and does not toggle back and forth. Below is the code.

JavaScript

Advertisement

Answer

The problem you’re having is that the background-color of an element is reported differently in browsers, either rgb, rgba (with, or without, spaces) in hex or in HSL…

So the button will likely never satisfy the if condition, meaning it will always go to the else.

With that in mind, I’d suggest using a class-name to keep track of the un/toggled state:

JavaScript

JS Fiddle demo.

Of course, if we’re using the class of the element, we might as well use CSS to style the element:

JavaScript

With the CSS:

JavaScript

JS Fiddle demo.

The previous JavaScript could be simplified (using the same CSS) to:

JavaScript

JS Fiddle demo.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement