The color-preview Stimulus controller provides a color picker interface that updates a preview element's color or background color.
By default, the controller updates the backgroundColor of the target element. It also automatically calculates the contrast using a YIQ algorithm to ensure foreground text remains readable by switching between black and white text colors.
To update the text color instead of the backgroundColor, add the data-color-preview-style-value="color" attribute to the controller element.
<div class="mt-3 flex items-center" data-controller="color-preview">
<!-- The preview element -->
<p data-color-preview-target="preview" class="h-10 w-10 mr-2 rounded-full text-2xl text-white text-center" style="background-color: #ba1e03; color: #fff; padding-top: 1px;">A</p>
<span class="ml-2">
<div class="flex rounded-md shadow-sm">
<span class="inline-flex items-center px-3 rounded-l-md border border-r-0 border-gray-300 bg-gray-50 text-gray-500">#</span>
<!-- The color input -->
<input data-action="input->color-preview#update"
data-color-preview-target="color"
id="hex_color_bg"
name="hex_color_bg"
type="color"
value="#ba1e03"
class="focus:ring-indigo-500 focus:border-indigo-500 block shadow-sm sm:text-sm border-gray-300 flex-1 rounded-r-md mt-0 w-24 h-8 px-1 py-1 border" />
</div>
</span>
</div>