I’m trying to change a div background color to a different color depending on what the div’s current color is, when the div is clicked on. The following code does not work. I’ve figured it has something to do with my “if” statements because it works fine if I just make them change to 1 color with no “if” statements.
<script language="JavaScript">
function setColor(blockId) {
if (document.getElementById(blockId).style.background == '#FF0000') {
document.getElementById(blockId).style.background = '#0000FF';
}else if (document.getElementById(blockId).style.background == '#0000FF') {
document.getElementById(blockId).style.background = '#999999';
}else if (document.getElementById(blockId).style.background == '#999999') {
document.getElementById(blockId).style.background = '#FF0000';
}
}
</script>
<div id="b1" style="background-color:#FF0000; height:100px; width:100px;" onClick="setColor('b1')"></div>
Increment an index to identify which background you are using from a list of backgrounds. You can store that index as a property on the element.
Also, rather than doing a lookup on that element via
document.getElementById(), just passthisfrom theonclickhandler, and your function has a reference to the element itself.Working demo: http://jsfiddle.net/gilly3/vPMPb/