A JavaScript class to read and output HTML/CSS colours in a variety of formats and compare then to other colours which may or may not be in the same format
The class' current state is stored in rgba format and can be set by a string representing a colour in any format specified by the W3C's CSS Colour Module Level 3.
The colour can then be output in any other format, or compared with any other colour representing string.
Please seek permission if you wish to distribute this in a modified form.
Please include the following line in the credits of any software you use this in or when re-distributing:
First things first: create an instance of the Colour class and initialise it to the background colour of an element (el):
c1 = new Colour( el.style.BackgroundColor() );If you are unsure about the reliability of the value you have given to the class, you can at any time check whether it was left in a valid state the last time it was set:
if(c1.isValid()){ // then received valid input}You can now get a string representation of the colour in any one of the supported formats:
c1.rgb; // rgb(r,g,b)c1.rgba; // rgba(r,g,b,a)c1.hsl; // hsl(h,s,l)c1.hsla; // hsla(h,s,l,a)c1.hex(); // #rrggbbc1.name; // eg: 'red', 'blue', 'orange'Now, the key reason behind this class: we can compare the Colour object with the value for something else regardless of the format that colour is in:
if( c1.compare( el2.style.backgroundColor() ) ){ //then colours are the same}Finally, an existing colour can have its state changed:
c1.set( el2.style.backgroundColor() )