HSL Color Cycling
Loop-based event handling with dynamic color generation
This example demonstrates a sophisticated pattern: using an event-driven loop
to continuously animate colors while the pointer is held down. Zero JavaScript required!
repeat until
pointerdown/pointerup
transition
Math.random()
template strings
Instructions: Press and hold on the box below. Watch the colors cycle while you hold! Release to stop.
Press & Hold Me!
The Code
<div id="color-box"
_="on pointerdown
set originalColor to my *background-color
repeat until event pointerup from the document
set rand to Math.random() * 360
transition
*background-color
to `hsl(${rand} 100% 90%)`
over 250ms
end
transition *background-color to originalColor
end">
Press & Hold Me!
</div>
How it works:
- Save original color:
set originalColor to my *background-color
- Start event loop:
repeat until event pointerup from the document
- Generate random hue:
set rand to Math.random() * 360
- Animate color:
transition *background-color to `hsl(${rand} 100% 90%)` over 250ms
- Loop continues until pointer is released
- Restore original:
transition *background-color to originalColor
Advanced Concepts:
- Event-driven loops:
repeat until event [eventName] creates loops that wait for events
- CSS property access:
my *background-color reads computed CSS properties
- Template strings:
`hsl(${rand} 100% 90%)` uses JavaScript template literal syntax
- Transitions:
transition [property] to [value] over [duration] creates smooth animations
- Global scope: Access
Math.random() and other JavaScript globals directly
- Event sources:
from the document listens on the document object
Why this pattern is powerful:
- No timers or intervals needed - event-driven by design
- Automatic cleanup when loop exits - no memory leaks
- Declarative control flow - easy to read and understand
- Smooth transitions handled by browser - hardware accelerated
Try it yourself:
- Change the transition duration:
over 500ms for slower color changes
- Modify the HSL values:
hsl(${rand} 80% 70%) for different saturation/lightness
- Add a counter:
increment #counter inside the loop to count cycles
- Try different events:
repeat until event keyup from the document