Skip to content

Commit

Permalink
add: Color contrast snippet
Browse files Browse the repository at this point in the history
  • Loading branch information
Yaya12085 committed Dec 31, 2024
1 parent d210bf6 commit d46072b
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion public/data/javascript.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}

]
},
{
Expand Down

0 comments on commit d46072b

Please sign in to comment.