Simple If Else statement to change div Color
i spent a few hours and can't get past this simple code, my first If works, but the else always fail once the bg color has changed to pink.
The initial color is red. If I click once, it turns into pink as expected. If I click again, (once the background has changed to pink), it does not do anything where as I would like it to change into Green, and then Pink, then Green
Any clues? am I using the wrong listener?
I would then call the above function in my window.onload = init;
wrapper = document.getElementById("wrapper");
if(wrapper.style.backgroundColor !== "Pink")
wrapper.style.backgroundColor = "Pink";
wrapper.style.backgroundColor = "Green";
Once you set the backgroundColor to "Pink" ... it converts it to RGB. So when you try to get the value again, you need to compare against that:
rgb(255, 192, 203)
It doesn't know what "Pink" is.
Right, as mentioned above the browser might manipulate the value you've given it into something it prefers, breaking your comparison later.
Instead you can try keeping track of the color/colors internally to your script...
<meta charset="utf-8" />
changeWrapperBackgroundColor = (function(cols)
document.getElementById('wrapper').style.backgroundColor = cols;
}(['pink', 'green', 'blue']));
window.addEventListener('click', changeWrapperBackgroundColor, false);
<div id="wrapper">Hello World</div>
Another way would be to use classes in the CSS. Here's a quick way with jQuery:
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread