javascript
55 lines · 7 steps
Building an accessible star-rating widget
A vanilla-JS class renders interactive stars and keeps hover, selection, and ARIA state in sync through a single paint method.
Explained by
highlit
1class StarRating {
2 constructor(container, { max = 5, value = 0, onChange } = {}) {
3 this.container = container;
4 this.max = max;
5 this.value = value;
6 this.hovered = 0;
7 this.onChange = onChange;
8 this.render();
9 this.bindEvents();
10 }
11
12 render() {
13 this.container.classList.add('star-rating');
14 this.container.innerHTML = Array.from({ length: this.max }, (_, i) =>
15 `<span class="star" data-index="${i + 1}" role="radio" tabindex="0" aria-label="${i + 1} star">\u2605</span>`
16 ).join('');
17 this.stars = [...this.container.querySelectorAll('.star')];
18 this.paint();
19 }
20
21 bindEvents() {
22 this.stars.forEach((star) => {
23 const index = Number(star.dataset.index);
24 star.addEventListener('mouseenter', () => {
25 this.hovered = index;
26 this.paint();
27 });
28 star.addEventListener('click', () => this.select(index));
29 star.addEventListener('keydown', (e) => {
30 if (e.key === 'Enter' || e.key === ' ') {
31 e.preventDefault();
32 this.select(index);
33 }
34 });
35 });
36 this.container.addEventListener('mouseleave', () => {
37 this.hovered = 0;
38 this.paint();
39 });
40 }
41
42 select(index) {
43 this.value = this.value === index ? index - 1 : index;
44 this.paint();
45 this.onChange?.(this.value);
46 }
47
48 paint() {
49 const active = this.hovered || this.value;
50 this.stars.forEach((star, i) => {
51 star.classList.toggle('filled', i < active);
52 star.setAttribute('aria-checked', String(i + 1 === this.value));
53 });
54 }
55}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Routing every visual update through one paint method keeps hover and selection state consistent without scattered DOM writes.
- 2Building interactive DOM from a data array lets index metadata drive both rendering and event logic.
- 3Adding role, tabindex, and aria-checked makes a custom widget usable by keyboard and screen readers.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-an-accessible-star-rating-widget-explained-javascript-58e3/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.