How can I change the colour of a button using JavaScript? -
i want change coilor of button on mouse click white red red white if click again. tried this:
<script language="javascript"> <!-- function changecolor(id){ var series = "0"; var = window.getcomputedstyle(document.getelementbyid(id)).backgroundcolor; var b = 2 if (a == "#ff4f4f") { b = 1 } if (b == 1) { document.getelementbyid(id).style.backgroundcolor = "#ffffff"; } if (b == 2) { document.getelementbyid(id).style.backgroundcolor = "#ff4f4f"; } } //--> </script> it won't work. make button go red in mozilla, chrome won't click white. ie says "error in page". button html code is:
<input type = "button" id = "01" value="01" onclick="changecolor('01')"> something missing css styles. looks first read (of colour) null value makes button go red -in 2 browsers- way function of mine constructed. looks if condition not working properly, see red , make white.
the computed style of background colour of format rgb(###, ###, ###) (or variations thereof, such different whitespace or rgba) therefore comparing #xxxxxx not work.
since you're assigning style.backgroundcolor, can read back:
var elem = document.getelementbyid(id); if( elem.style.backgroundcolor == "#ff4f4f") { elem.style.backgroundcolor = "#ffffff"; } else { elem.style.backgroundcolor = "#ff4f4f"; } feel free switch cases around needed (based on how should change first time), work because browser keep whatever assigned it.
however, in general, should have more reliable toggle:
var elem = document.getelementbyid(id); if( elem._toggle) { elem.style.backgroundcolor = "#ffffff"; } else { elem.style.backgroundcolor = "#ff4f4f"; } elem._toggle = !elem._toggle; this toggle reliably.
Comments
Post a Comment