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.
function btnColor(btn, color) { var property = document.getElementById(btn); if (property.style.backgroundColor == "rgb(244,113,33)") { property.style.backgroundColor=color; } else { property.style.backgroundColor = "rgb(244,113,33)"; } } <input type="button" id="btnHousing" value="Housing" onclick="toggleLayer('transparent1');btnColor('btnHousing','rgb(255,242,0)');" />
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:
function btnColor(btn, color) { var property = document.getElementById(btn); if (property.className !== 'toggled') { property.style.backgroundColor=color; property.className = 'toggled' } else { property.style.backgroundColor = "rgb(244,113,33)"; property.className = ''; } }
Of course, if we’re using the class
of the element, we might as well use CSS to style the element:
function btnColor(btn) { var property = document.getElementById(btn); if (property.className !== 'toggled') { property.className = 'toggled' } else { property.className = ''; } }
With the CSS:
#btnHousing { background-color: rgb(255,242,0); } #btnHousing.toggled { background-color: rgb(244,113,33); }
The previous JavaScript could be simplified (using the same CSS) to:
function btnColor(btn) { var property = document.getElementById(btn); property.className = 'toggled' == property.className ? '' : 'toggled'; }