Testing Colours
Join the Discussion
When you set a color or background colour in your stylesheet either by coding it there directly or by setting it via Javascript there are a number of different ways that you can supply the information as to exactly what colour you are setting. In fact there are four different ways to set colours. Let's take a look at examples of these four ways:
color:#ffffff
background-color:#000
color:rgb(255, 0, 0)
These same four methods can be used to set colours and background colours from within your Javascript code.
You would expect that having set the colour using a specific method that you can then test the colour from within Javascript using that same method or consistently using a specific method. Unfortunately that isn't the way that it works. Which format the colour is in when you look it up depends on which browser you are using to do the lookup and so when coding to test for a specific colour we need to allow for any of the three formats in which the browsers might return the colour to us.
In my Piano Chord Calculator script I needed to test whether the piano keys are their original black and white colours or whether they had been highlighted in a different colour. To perform this test I not only need to test for both black and white in all three different versions I also need to test for nothing being returned as will be the case if the colour has been set within the stylesheet and not yet changed from within the Javascript. Here is the if statement that I ended up with to test for these two colours.
if (cl != '' && cl != '#000000' && cl != '#ffffff'
&& cl != '#000' && cl != '#fff' && cl != 'rgb(0, 0, 0)'
&& cl != 'rgb(255, 255, 255)')
The colours of the keys are reset as required using the shortest version of the code (#000 and #fff) but that doesn't stop the different browsers from converting those into their favourite format and returning that instead and I therefore end up with seven comparisons (including '') instead of the two that most people would expect to need for this code.

