Working with color in JavaScript

Working with color in JavaScript requires some understanding of color formats and conversions. This snippet collection covers a lot of those needs from generating random color hex codes to converting between hex and RGB values and even some more advanced tricks like using the HSL format to alter the lightness of a color.

  • randomHexColorCode

    JavaScript, Math

    Generates a random hexadecimal color code.

  • RGBToHex

    JavaScript, String

    Converts the values of RGB components to a hexadecimal color code.

  • extendHex

    JavaScript, String

    Extends a 3-digit color code to a 6-digit color code.

  • hexToRGB

    JavaScript, String

    Converts a color code to an rgb() or rgba() string if alpha value is provided.

  • toRGBArray

    JavaScript, String

    Converts an rgb() color string to an array of values.

  • toRGBObject

    JavaScript, String

    Converts an rgb() color string to an object with the values of each color.

  • RGBToHSB

    JavaScript, Math

    Converts a RGB color tuple to HSB format.

  • HSBToRGB

    JavaScript, Math

    Converts a HSB color tuple to RGB format.

  • RGBToHSL

    JavaScript, Math

    Converts a RGB color tuple to HSL format.

  • HSLToRGB

    JavaScript, Math

    Converts a HSL color tuple to RGB format.

  • changeLightness

    JavaScript, String

    Changes the lightness value of an hsl() color string.

  • toHSLArray

    JavaScript, String

    Converts an hsl() color string to an array of values.

  • toHSLObject

    JavaScript, String

    Converts an hsl() color string to an object with the values of each color.