Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Create a Function to Convert JS Numbers into CSS Hex Colors


    JavaScript numbers and CSS hexadecimal numbers don't play very well together. You can solve this with a conversion function that takes the number, converts it to a string, then pads the string with the necessary zeroes at the start using padStart.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    John Lindquist: You express blue in hexadecimal with 0x0000ff, but if you were to log this out in the console.log(blue) and you'll see 255. That's because 255 is the same as 0x0000ff, hit save, you'll see that's true or if I just remove the zeros, hit save and that's true. These zeros are just padded on the left, which are essentially placeholders for red and green.

    To display blue, I'm going to on the document.body.style, change the backgroundColor to be the hash version of a hexadecimal, so #0000ff, hit save and we have our blue and the padded zeros are required. If I remove them here, this turns to white, so add the zeros back in.

    To use this blue here, if I tried to just say use blue, that's not going to work because it's going to try and make this a 255. To change it to fs, I can change this to hexadecimal with toString(16), which represents hexadecimal. I'll hit save and now we're back to the color blue.

    Then also here to make sure we have enough zeros instead of manually typing them out, we can take our string of ff and say padStart and the number of characters required are six, two for red, two for green, two for blue and then we want to pad it with zeros if there's anything less.

    Now that we have this setup, we can extract this to a function. I'll paste this up here and just name the function toHex() and this will take a color and then output color toString with the padStart. I can say toHex(blue), hit save and we have blue again. If I create green, so 0x00ff00 and paste in green here, we'll now get our green. Finally, red can be 0xff0000 and try red here and now we have our red.