goldies
    Preparing search index...

    Function getContrastColor

    • Determines the optimal contrast color (black or white) for text displayed on a given background color.

      Uses the YIQ color space formula to calculate perceived brightness and returns either black (#000000) or white (#ffffff) for maximum readability.

      Parameters

      • hexCode: string = '#008000'

        A 3 or 6 character hexadecimal color code. The leading # is optional. Defaults to #008000 (green) if not provided.

      Returns string

      The contrasting color as a 6-character hex string with leading #. Returns #000000 (black) for light backgrounds or #ffffff (white) for dark backgrounds.

      // With 6-digit hex code
      getContrastColor('#ff0000');
      // => '#ffffff'
      // With 3-digit shorthand hex code
      getContrastColor('000');
      // => '#ffffff'
      // Light background returns black text
      getContrastColor('#ffffff');
      // => '#000000'
      // Dark background returns white text
      getContrastColor('#000000');
      // => '#ffffff'
      // Using default value
      getContrastColor();
      // => '#ffffff'