Last active
February 20, 2024 13:10
-
-
Save crispyabsurdist/fe537a09a88002c21846e8175c47c939 to your computer and use it in GitHub Desktop.
alpinejs contrast setting text-color and border-color depending on background-color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="bg-{{ $backgroundColor }}" x-data="colorContrast()" x-bind:class="textColorClass"> | |
<p>Text som ska ändra färg beroende på bakgrundsfärg</p> | |
<a class="leading-non inline-block rounded-3xl border px-6 py-4 text-xs font-bold no-underline" href="{{ $card['card_button']['url'] }}" x-bind:class="borderColorClass"> | |
{{ $card['card_button']['title'] }} | |
</a> | |
</div> | |
<script> | |
document.addEventListener('alpine:init', () => { | |
Alpine.data('colorContrast', () => ({ | |
textColorClass: 'text-black', | |
borderColorClass: 'border-black', | |
init() { | |
this.$nextTick(() => { | |
this.determineClass('text'); | |
this.determineClass('border'); | |
}); | |
}, | |
determineClass(property) { | |
const style = getComputedStyle(this.$el); | |
const rgb = style.backgroundColor; | |
const matches = rgb.match(/\d+/g); | |
if (matches) { | |
const [r, g, b] = matches.map(Number); | |
const brightness = (r * 299 + g * 587 + b * 114) / 1000; | |
this[`${property}ColorClass`] = brightness < 128 ? `${property}-white` : | |
`${property}-black`; | |
} | |
} | |
})); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment