Skip to content

Commit 404afa9

Browse files
authored
Merge pull request #47 from Yaya12085/color-contrast
add: Color contrast snippet
2 parents e4fafc3 + d46072b commit 404afa9

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

public/data/javascript.json

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,33 @@
355355
],
356356
"tags": ["javascript", "utility", "throttle", "performance"],
357357
"author": "dostonnabotov"
358-
}
358+
},
359+
{
360+
"title": "Get Contrast Color",
361+
"description": "Returns either black or white text color based on the brightness of the provided hex color.",
362+
"code": [
363+
"const getContrastColor = (hexColor) => {",
364+
" // Expand short hex color to full format",
365+
" if (hexColor.length === 4) {",
366+
" hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`;",
367+
" }",
368+
" const r = parseInt(hexColor.slice(1, 3), 16);",
369+
" const g = parseInt(hexColor.slice(3, 5), 16);",
370+
" const b = parseInt(hexColor.slice(5, 7), 16);",
371+
" const brightness = (r * 299 + g * 587 + b * 114) / 1000;",
372+
" return brightness >= 128 ? \"#000000\" : \"#FFFFFF\";",
373+
"};",
374+
"",
375+
"// Usage:",
376+
"console.log(getContrastColor('#fff')); // Output: #000000 (black)",
377+
"console.log(getContrastColor('#123456')); // Output: #FFFFFF (white)",
378+
"console.log(getContrastColor('#ff6347')); // Output: #000000 (black)",
379+
"console.log(getContrastColor('#f4f')); // Output: #000000 (black)"
380+
],
381+
"tags": ["color", "hex", "contrast", "brightness", "utility"],
382+
"author": "yaya12085"
383+
}
384+
359385
]
360386
},
361387
{

0 commit comments

Comments
 (0)