A slider lets users drag a thumb across a track to select a value. As a custom Web Component, <wcia-slider> turns that familiar control into reusable UI logic. section 2.4 section 3.6
Build the component incrementally:
- Extend HTMLElement with a Slider class and register it as wcia-slider through the Custom Element API. section 2.4
- Render an overlay and thumb, then style the host, track, and thumb directly through the component DOM. section 2.4
- Expose value as a 0–100 percentage and backgroundcolor as a hexadecimal color, reflecting properties through attributes. section 3.6
- React to attribute changes with attributeChangedCallback, positioning the thumb and updating the overlay gradient. section 3.6
- Handle mousedown, mousemove, and mouseup events, clamp pointer positions to the track, and update value while dragging. section 3.6
- Separate template, component, and demo files, then move initialization into a Shadow DOM constructor for encapsulated markup and styling. section 6.7 section 9.5
Configuring a transparency slider
Use <wcia-slider backgroundcolor="#0000ff" value="70"></wcia-slider> to render a blue slider initialized at 70 percent. Changing the value attribute or property refreshes the thumb position; dragging updates the value attribute. section 3.6
Listing 9.14. Slider component constructor
constructor() { #1
super();
this.attachShadow({mode: 'open'}); #2
this.shadowRoot.innerHTML =
Template.render(); #3
this.dom = Template.mapDOM(this.shadowRoot);
document.addEventListener('mousemove', e => this.eventHandler(e));
document.addEventListener('mouseup', e => this.eventHandler(e));
this.addEventListener('mousedown', e => this.eventHandler(e));
}
Inspect the Shadow DOM constructor that attaches an open shadow root, renders the template, maps internal elements, and installs pointer listeners. section 9.5
