From d46072ba614e7bfa8dbd6934f329b6ad57767f47 Mon Sep 17 00:00:00 2001 From: Yaya12085 Date: Tue, 31 Dec 2024 01:17:59 +0000 Subject: [PATCH] add: Color contrast snippet --- public/data/javascript.json | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/public/data/javascript.json b/public/data/javascript.json index f50cd4c4..828b25e9 100644 --- a/public/data/javascript.json +++ b/public/data/javascript.json @@ -355,7 +355,33 @@ ], "tags": ["javascript", "utility", "throttle", "performance"], "author": "dostonnabotov" - } + }, + { + "title": "Get Contrast Color", + "description": "Returns either black or white text color based on the brightness of the provided hex color.", + "code": [ + "const getContrastColor = (hexColor) => {", + " // Expand short hex color to full format", + " if (hexColor.length === 4) {", + " hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`;", + " }", + " const r = parseInt(hexColor.slice(1, 3), 16);", + " const g = parseInt(hexColor.slice(3, 5), 16);", + " const b = parseInt(hexColor.slice(5, 7), 16);", + " const brightness = (r * 299 + g * 587 + b * 114) / 1000;", + " return brightness >= 128 ? \"#000000\" : \"#FFFFFF\";", + "};", + "", + "// Usage:", + "console.log(getContrastColor('#fff')); // Output: #000000 (black)", + "console.log(getContrastColor('#123456')); // Output: #FFFFFF (white)", + "console.log(getContrastColor('#ff6347')); // Output: #000000 (black)", + "console.log(getContrastColor('#f4f')); // Output: #000000 (black)" + ], + "tags": ["color", "hex", "contrast", "brightness", "utility"], + "author": "yaya12085" +} + ] }, {