Here's how you can create a slider component in Svelte 5 using its syntax and features, including runes for reactivity and accessible state sharing. The slider will display its value on hover and allow the parent component to access and update the value.
Slider Component: Slider.svelte
[Redacted
<script>
// Exporting the slider's state so it can be accessed from the parent
export let value = 50; // Default value (range: 0 to 100)
let isHovered = false; // Tracks hover state
</script>
<div
class="slider-container"
on:mouseenter={() => (isHovered = true)}
on:mouseleave={() => (isHovered = false)}
>
<input
type="range"
bind:value
min="0"
max="100"
step="1"
class="slider"
/>
{#if isHovered}
<div class="tooltip">{value}</div>
{/if}
</div>
<style>
.slider-container {
position: relative;
width: 100%;
max-width: 300px;
}
.slider {
width: 100%;
}
.tooltip {
position: absolute;
top: -30px;
left: 50%;
transform: translateX(-50%);
background-color: #333;
color: white;
padding: 5px 10px;
border-radius: 4px;
font-size: 14px;
white-space: nowrap;
pointer-events: none;
}
</style>
Parent Component: App.svelte
[Redacted
<script>
import Slider from './Slider.svelte';
let sliderValue = 30; // Default value for the slider
</script>
<main>
<h1>Slider Example</h1>
<Slider bind:value={sliderValue} />
<p>Selected value: {sliderValue}</p>
</main>
<style>
main {
font-family: Arial, sans-serif;
text-align: center;
margin: 50px auto;
width: 300px;
}
h1 {
font-size: 24px;
margin-bottom: 20px;
}
p {
margin-top: 20px;
font-size: 18px;
}
</style>
Key Features of the Implementation:
Bidirectional Binding with bind:value:
The value prop in the Slider.svelte component is bound to the parent component using Svelte's bind: syntax. This ensures that any change to the slider's value is immediately reflected in the parent component, and vice versa.
Hover State with isHovered:
The isHovered local state determines whether the tooltip showing the current value is visible. The on:mouseenter and on:mouseleave event handlers toggle this state.
Styling for Tooltip and Slider:
The tooltip is styled to appear above the slider on hover, centered relative to the slider's thumb.
Accessibility:
The slider's value is displayed in real-time to the parent component, making it easier to integrate into larger applications.
How It Works:
The Slider.svelte component defines a slider input and exports a value prop.
When the user interacts with the slider, the value is updated, and the parent component receives the changes via bind:value.
On hover, the current slider value is displayed in a tooltip above the slider.
This implementation uses pure Svelte 5 syntax and is modular, reusable, and accessible. If needed, you can further enhance it with custom events or styles.