Jonohues
crafting a web-safe color-picker in Svelte
// updated 2026-01-08 14:48
Users can browse colors by controlling the sliders:
- the background color of the rectangular box changes with the sliders
- the rgb and hex codes of the color display below the box
Demo
Working demo below:
Code
Reflecting upon the source code, removing any unnecessary details of the source code to highlight the essentials:
<!-- Hue.svelte -->
<script>
// sub-component
import Slider from "./Slider.svelte";
// color values controlled by sliders
export let red = 0;
export let green = 0;
export let blue = 0;
// ensure that hex codes always have 2 "digits" for each of the red + green + blue
let d2h = value => {
return value.toString(16).padStart(2,'0');
};
</script>
<main>
<!-- Svelte variables allow users to change colors with the sliders -->
<div class="sliders">
<p>red: <Slider color="red" bind:intensity={red} /></p>
<p>green: <Slider color="green" bind:intensity={green} /></p>
<p>blue: <Slider color="blue" bind:intensity={blue} /></p>
</div>
<!-- Svelte variables change the rectangle's background color -->
<div class="rectangle" style="background: rgb({red},{green},{blue}"></div>
<!-- Svelte variables control the HTML text -->
<div class="rgb-code">rgb({red},{green},{blue})</div>
<div class="hex-code">hex: #{d2h(red)}{d2h(green)}{d2h(blue)}</div>
</main>
<style>
/* see repo for CSS (not touched by Svelte code) */
</style><!-- Slider.svelte -->
<script>
export let color;
export let intensity = 0;
</script>
<input style="accent-color: {color}" type="range" min="0" max="255" bind:value={intensity} />
<style>
input {
width: 100%;
}
</style>Increased familiarity with:
- parent and child components
- formatting text
- binding variables from child components to parent components
- variables that control text and style
- the Svelte component file layout of scripting + structuring + styling