0

I have the following JSON data:

 {
   "name": "faded",
   "artist": "alan walker",
   "color": "faded"
 },
 {
   "name": "i love you",
   "artist": "omfg",
   "color": "143"
 },
 {
   "name": "closer",
   "artist": "the chainsmokers",
   "color": "c105e2"
 },
 {
   "name": "roses",
   "artist": "the chainsmokers",
   "color": "205e2"
 }

I'm converting hex codes into background-colors, however some of these will not work since colors needs be either a 6-digit (#ffffff) or 3-digit number (#fff).

A solution would be to add 0 before numbers which are 2,4 or 5 digits only, so "205e2" would come out as "#0205e2". I'd also like to apply this JSON data to each div:

<div style="background-color: #000;"> <!-- background-color here -->
    <h1 id="name"></h1> <!-- name goes here -->
    <h2 id="artist"></h2> <!-- artist goes here -->
    <h3 id="hex">#000000</h3><!-- color text goes here -->
    <div class="content">
    <button>Like</button>
    <button>Copy</button>
</div>

What would be the possible way to code this?

  • `205e2` is an invalid color value so why are you expecting that as your color? – Muhammad Nov 26 '16 at 19:19
  • And if you add `0` at the beginning of the value it will become some unexpected color if you don't have proper acknowledgment from where you receive the JSON data. – Muhammad Nov 26 '16 at 19:27
  • http://stackoverflow.com/questions/8027423/how-to-check-if-a-string-is-a-valid-hex-color-representation in the above answer you can see how to validate 3 and 6 digit hex colors. – Muhammad Nov 26 '16 at 19:28
  • yes @Muhammad it's an invalid color value. that's why i'm adding 0 to make it valid even if the color is unexpected. – Tactician Jenro Nov 27 '16 at 04:54
  • But thats not a good solution I think. anyway you con go with it if it works for you. – Muhammad Nov 27 '16 at 04:57

0 Answers0