Skip to content

Instantly share code, notes, and snippets.

@SamuelNunesDev
Last active May 11, 2023 12:21
Show Gist options
  • Save SamuelNunesDev/ca0426fa193ba5bce105306a98f58a26 to your computer and use it in GitHub Desktop.
Save SamuelNunesDev/ca0426fa193ba5bce105306a98f58a26 to your computer and use it in GitHub Desktop.
Darken a color in hex useful for dynamically creating a hover effect using only js. Ex: handleDarkenColor('#21FEEB') or handleDarkenColor('#ccc')
function handleDarkenColor(hex) {
let strHex = hex
if(![4, 7].includes(hex.length)) return '#171773'
else if(hex.length == 4) {
let newHex = '#'
hex.slice(1).split("").forEach((c) => {
newHex += c + c
})
strHex = newHex
}
let rgb = [
[1, 3],
[3, 5],
[5, 7]
]
let int
rgb = rgb.map(attr => {
int = parseInt(strHex.slice(attr[0], attr[1]), 16)
int = int - 50 >= 0 ? int - 50 : 0
return int.toString(16).padStart(2, '0')
})
return `#${rgb.join('')}`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment