Real problematic
Write a function that returns a color value from any CSS color OR from a color defined by a class
Initial wording
I would like to know if the string passed in the parameter of my function matches the color β the answer is just that would be great β and then know its hexadecimal value.
So, I defined a regex to find out if a string is something like #fff or also rgb(0,0,0) , but it does not recognize standard CSS colors like black and white . Do I have to test every color name or is there any way or a pre-existing function exists? Thanks.
Personal solution
- If you want class names preceding dots, such as ".myClass"
function getColor(classOrColor) { if(classOrColor[0] === '.') { var temp = $('<div id="temp" style="display:none;" class="'+ classOrColor.split('.').join(' ') + '"/>').appendTo('body'); var color = temp.css('color'); temp.remove(); return color; } else { return classOrColor; } }
Examples of using:
getColor('yellow') getColor('#abc') getColor('rgb(1,2,3)') getColor('.myClass .myOtherClass')
Mplungjan answer based solution
- If you want simple class names such as "myClass"
Search if a class with that name exists with this answer: https://stackoverflow.com/a/316829/
Then call the same function (with minor modification)
function getColor(classOrColor) { if(classExists(classOrColor)) { var temp = $('<div id="temp" style="display:none;" class="'+ classOrColor + '"/>').appendTo('body'); var color = temp.css('color'); temp.remove(); return color; } else { return classOrColor; } }
Examples of using:
getColor('#abc') getColor('myClass')
source share