Svelte 5 offers an elegant and efficient way to build interactive web applications, and a color picker is a perfect example to demonstrate its capabilities. In this blog post, we’ll explore how to create an interactive color picker using Svelte 5, focusing on a simple yet functional code snippet.
<script> import Svg from '../lib/assets/circle.svg'; let colors = $state(['#BBFF00', '#06F586', '#ff3e00', '#8D462E', '#FF0037']); let fillings = $state(0); $effect(() => { console.log(fillings); }); </script> <div> <div class="flex gap-2 mb-4"> {#each colors as color, index} <div class="flex flex-col gap-2"> <button onclick={() => (fillings = index)} style:background={colors[index]} class="w-24 h-24 mb-3 rounded-full" > {#if index === fillings} <img src={Svg} alt={index.toString()} /> {/if} </button> <span> <code> {colors[index]} </code> </span> </div> {/each} </div> <input bind:value={colors[fillings]} type="color" name="color" /> </div>
The provided code creates a color picker interface where users can select from a set of predefined colors. Here’s how it works:
import Svg from '../lib/assets/circle.svg';
let colors = $state(['#BBFF00', '#06F586', '#ff3e00', '#8D462E', '#FF0037']);
let fillings = $state(0);
$effect(() => { console.log(fillings); });
{#each colors as color, index} <button onclick={() => (fillings = index)} style:background={colors[index]} class="w-24 h-24 mb-3 rounded-full"> {#if index === fillings} <img src={Svg} alt={index.toString()} /> {/if} </button> {/each}
<input bind:value={colors[fillings]} type="color" name="color" />
With this simple setup, users can easily choose a color, and the real-time feedback enhances engagement. The SVG icon provides a visual representation of the selected color, making the interface more intuitive.
Creating an interactive color picker in Svelte 5 is a straightforward process that showcases the framework's strengths in reactivity and simplicity. This example can serve as a foundation for more complex applications, allowing developers to build on this basic functionality with additional features, such as saving color preferences or integrating with design tools. With Svelte, the possibilities are endless, making it a fantastic choice for modern web development.
The above is the detailed content of Creating an Interactive Color Picker with Svelte 5. For more information, please follow other related articles on the PHP Chinese website!