Adium.js Documentation
API reference for adium.js v2.1.0.
Quick Start
Add the script (adium.min.js), a box, and a minimal config. The unit fires onImpression, onEngagement, and onComplete so you can forward those events to your own tools.
<script src="adium.min.js"></script> <div id="adium-box" style="width:600px;height:400px"></div> <script> const ad = new Adium({ target: document.getElementById('adium-box'), movementTypes: ['mouse', 'touch'], interactionTypes: ['click', 'tap'], media: { background: 'bg.png', sprite: { image: 'sprite.png', size: { width: 48, height: 48 } }, completion: 'complete.png' }, onImpression: function (data) { /* forward to your own tools */ }, onEngagement: function (data) { /* forward to your own tools */ }, onComplete: function (data) { /* forward to your own tools */ } }); // The same events are also available on the bus: // ad.on('impression', function (e) { /* forward to your own tools */ }); // ad.on('engagement', function (e) { /* forward to your own tools */ }); // ad.on('complete', function (e) { /* forward to your own tools */ }); </script>
A click or tap on the box completes the moment and shows the reveal. Only target and media are required. To complete by moving the sprite into a goal, add landingZones.
There is no build step and no package dependencies.
Full HTML Example
A complete page with the same minimal config, including the callbacks the unit fires.
<!DOCTYPE html> <html> <body> <div id="adium-box" style="width:300px;height:250px;"></div> <script src="adium.min.js"></script> <script> const ad = new Adium({ target: document.getElementById('adium-box'), media: { background: 'bg.png', backgroundSize: 'cover', sprite: { image: 'sprite.png', size: { width: 48, height: 48 } }, completion: 'complete.png' }, movementTypes: ['mouse', 'touch'], interactionTypes: ['click', 'tap'], completionTransition: 'fade', transitionDuration: 600, onImpression: function (data) { /* forward to your own tools */ }, onEngagement: function (data) { /* forward to your own tools */ }, onComplete: function (data) { /* forward to your own tools */ } }); </script> </body> </html>
How It Works
Adium renders an interactive experience inside a box you own on the page. The lifecycle follows four phases:
- Preload — Assets load based on
preloadMode(full, partial, or none). A branded spinner and loading text display while images and video buffer. IflazyInitis set, loading starts when at least 10% of the box is visible (IntersectionObserverthreshold0.1). - Init — Background applied, sprite created and centered, movement and interaction listeners bound, border and badge rendered. The
readyevent fires andonReadycallback runs. The instance is now interactive. - Interaction — The user moves the sprite and/or triggers a completion interaction. Every interaction emits an
interactionevent. The first interaction also firesengagement(once). If frustration detection is enabled, the system begins scoring user behavior for signs of confusion. - Completion — Transition plays (fade, confetti, zoom, etc.), completion media replaces the background,
onCompletefires. If segments are defined, the next segment loads instead of completing. If the triggering zone has asegmentIndexor its owncompletion, those are used instead of the defaults.
media.completion, the sprite hides and the background stays. For a video unit, the background clip can be the reveal.Config Object Map
The config object you pass to new Adium(config) has this structure. Every section of this documentation shows its config path in the heading so you always know where a property lives.
target: Element, REQUIRED
media: { REQUIRED
background, backgroundSize, backgroundColor,
sprite: { image, size: { width, height }, videoProgressBar: {...} },
completion,
videoLoop, videoMuted,
videoProgressBar: { enabled, height, color, backgroundColor, direction, position },
completionVideoLoop, completionVideoMuted,
completionVideoProgressBar: { ... }
},
movementTypes: [],
interactionTypes: [],
landingZones: [{ type, x, y, id, segmentIndex, completion, onEnter, ... }],
autoCompleteOnZone, completionTransition, transitionDuration,
borderStyle, borderColor, borderWidth,
badge: { text, position, color, textColor, fontSize, padding, borderRadius, opacity },
segments: [{ media, landingZones, movementTypes, ... }],
frustration: { enabled, sensitivity, escalation: [], hintText, ... },
audioControl: { enabled, position, size, color, backgroundColor },
preloadMode, autoResize, lazyInit, debug,
platformOverrides: { desktop, mobile, safari, ... },
onComplete, onReady, onSegmentComplete, onImpression, onEngagement, ...
}
Root Config Properties
These properties sit directly on the top-level config object you pass to the constructor.
config.*
| Property | Type | Description |
|---|---|---|
| target | Element | Required. The DOM element Adium renders into. Must have explicit width and height (inline style, CSS class, or parent constraint). |
| media | Object | Required. All visual assets — background, sprite, completion. See Media & Assets. |
| movementTypes | string[] | How the sprite moves: 'mouse', 'touch', 'drag', etc. Default: []. See Movement Types. |
| interactionTypes | string[] | What triggers completion: 'click', 'tap', 'swipe', etc. Default: []. See Interaction Types. |
| landingZones | Object[] | Target areas for zone-based completion. Default: []. See Landing Zones. |
| autoCompleteOnZone | boolean | Auto-complete when sprite enters a landing zone. Default: true. |
| completionTransition | string | Transition effect when showing completion. See Transitions. |
| transitionDuration | number | Transition time in ms. Default: 1000. |
| borderStyle | string | Decorative border around the container. See Borders. |
| borderColor | string | Border color. Use 'auto' to detect from parent. Default: brand blue. |
| borderWidth | number | Border thickness in px. Default: 10. |
| badge | Object | Floating text label overlay. See Badge. |
| segments | Object[] | Multi-level experience. See Segments. |
| frustration | Object | Frustration detection system. See Frustration Detection. |
| audioControl | Object | Audio mute/unmute button for video ads. See Audio Control. |
| preloadMode | string | 'full' (all assets), 'partial' (critical only, default), or 'none' (lazy load everything). |
| autoResize | boolean | Re-resolve %-based sizes on container resize via ResizeObserver. Default: false. See Auto Resize. |
| lazyInit | boolean | Delay initialization until at least 10% of the box is visible (IntersectionObserver threshold 0.1). Default: false. |
| viewability | Object | Optional. { threshold, durationMs } for the 'viewable' event: the share of the container's pixels that must be in view (0 < threshold ≤ 1, default 0.5) for this many continuous milliseconds (default 1000). See Event Bus. |
| debug | boolean | Enable verbose console logging for all internal events. Default: false. |
| platformOverrides | Object | Platform-specific code blocks. Keys: desktop, mobile, tablet, chrome, safari, ios, etc. See Platform Detection. |
| keyboardSpeed | number | Px per frame for keyboard movement. Default: 5. |
| scrollSpeed | number | Mouse wheel movement multiplier. Default: 2. |
| gyroSensitivity | number | Device tilt movement multiplier. Default: 5. |
| gamepadDeadzone | number | Gamepad stick deadzone (0–1). Default: 0.15. |
| hoverDuration | number | Milliseconds of hover required to trigger completion. Default: 1000. |
| longPressDuration | number | Milliseconds to hold for longPress interaction. Default: 500. |
| swipeThreshold | number | Pixel distance to register a swipe. Default: 50. |
| doubleTapDelay | number | Max ms between taps for doubleTap. Default: 300. |
| shakeThreshold | number | Accelerometer delta to trigger shake. Default: 15. |
| loadingText | string | Text shown on the loading screen spinner. Default: "Loading...". |
| loadingBackground | string | Loading screen background color. Default: Adium brand dark (#0f172a). |
| autoMatchBackground | boolean | Auto-extract the dominant color from the background image and set it as the container's CSS background-color (fills letterbox gaps). Default: false. |
Callbacks
Config-level callback functions. All are optional. For dynamic event handling after init, use the Event Bus instead.
config.*
| Property | Signature | When it fires |
|---|---|---|
| onComplete | (payload) => void | Ad completed (the last level finished). Receives the same { instanceId, timestamp, timeToComplete, skipped } payload as the 'complete' event (a callback that takes no arguments keeps working). |
| onSegmentComplete | (index, segment) => void | A level finished, before the next one loads. index is the finished segment's position (0-based) and segment is its config object. Fires once per finished level; the last level fires onComplete instead. |
| onReady | (instance) => void | Init finished, assets loaded, ready for interaction. Receives the Adium instance. |
| onInteraction | (type, data) => void | Every interaction event (click, swipe, hover, etc.). type is the interaction name, data contains coordinates or direction. |
| onImpression | ({instanceId}) => void | Fires once per instance: when init completes, or with lazyInit, when at least 10% of the box is visible. The callback receives { instanceId }. Adium does not send this event itself; forward it to your own tools if you want to. |
| onEngagement | ({interactionType, timeToEngage}) => void | First meaningful user interaction (fires once). timeToEngage is milliseconds since impression. |
| onViewable | (payload) => void | The container became viewable (fires once). Same payload as the 'viewable' event. |
| onVideoComplete | ({type, video}) => void | A non-looping video finishes playing. type is 'background' or 'completion'. video is the HTMLVideoElement. |
| onPermissionRequest | (type, config) => void | Before a permission dialog is shown. type is 'deviceOrientation', 'deviceMotion', etc. |
| onPermissionGranted | (type) => void | A browser permission was granted. |
| onPermissionDenied | (type, reason) => void | A browser permission was denied or errored. |
ad.on('complete', fn)) lets you add and remove multiple listeners at any point, and supports chaining.Media & Assets
The media object defines all visual and video assets. Background, sprite, and completion each accept both image URLs (.png, .jpg, .svg, .gif, .webp) and video files (.mp4, .webm, .ogg, .mov — auto-detected by extension).
config.media.*
| Property | Type | Description |
|---|---|---|
| background | string | URL of background image or video. Fills the container. For video, it auto-plays muted by default. |
| backgroundSize | string | 'cover' (fills, may crop — default), 'contain' (fits, may letterbox), 'stretch' (exact fill, may distort), or 'auto' (natural size). |
| backgroundColor | string | Fallback CSS color behind the background. Visible during loading or around contained images. |
| completion | string | URL of completion image or video. Shown after the user completes the ad. Optional — if omitted, the sprite hides and the background stays. |
| videoLoop | boolean | Loop the background video. Default: true. |
| videoMuted | boolean | Mute the background video. Default: true. Set false with audioControl for sound-on experiences. |
| completionVideoLoop | boolean | Loop the completion video. Default: true. |
| completionVideoMuted | boolean | Mute the completion video. Default: true. |
Sprite
The sprite is the movable element the user interacts with — it can be a product image, a cursor, a logo, or even a video. It's created from the media.sprite config and starts centered in the container.
config.media.sprite.*
| Property | Type | Description |
|---|---|---|
| image | string | URL of sprite image or video file. |
| size | Object | { width, height } — accepts px numbers (48), percentage strings ('15%'), viewport units ('10vw'), or 'auto'. |
| videoProgressBar | Object | Progress bar for a video sprite. Same shape as Video Progress Bar. |
// Pixel-based (fixed size, crisp control) sprite: { image: 'icon.png', size: { width: 48, height: 48 } } // Percentage of container (responsive — use with autoResize) sprite: { image: 'icon.png', size: { width: '12%', height: '12%' } } // Viewport units (scales with browser window) sprite: { image: 'icon.png', size: { width: '5vw', height: '5vw' } } // Video sprite with its own progress bar sprite: { image: 'character.mp4', size: { width: 80, height: 80 }, videoProgressBar: { height: 2, color: '#f1c40f' } }
Video Progress Bar
A thin progress indicator for background and/or completion videos. Each lives inside the media object next to the video it controls.
config.media.videoProgressBar.*
| Property | Type | Default | Description |
|---|---|---|---|
| enabled | boolean | true | Show the progress bar. |
| height | number | 5 | Bar height in px. |
| color | string | '#4a90e2' | Fill color of the progress bar. |
| backgroundColor | string | 'rgba(0,0,0,0.5)' | Track background color. |
| direction | string | 'normal' | 'normal' fills left→right. 'countdown' shrinks right→left (great for time-remaining). |
| position | string | 'bottom' | 'bottom' or 'top'. |
The completion video has its own bar at config.media.completionVideoProgressBar with the same properties. Video sprites use config.media.sprite.videoProgressBar.
media: { background: 'hero.mp4', videoLoop: false, videoProgressBar: { enabled: true, height: 3, color: '#f1c40f', position: 'bottom' }, completion: 'reveal.mp4', completionVideoProgressBar: { enabled: true, color: '#22c55e', direction: 'countdown' } }
Movement Types
Control how the sprite moves within the container. Set one or more values in the movementTypes array. Multiple types can be active simultaneously (e.g. mouse on desktop + touch on mobile).
config.movementTypes[]
| Value | Behavior | Tuning property |
|---|---|---|
| 'mouse' | Sprite follows mouse cursor position inside the container. | — |
| 'touch' | Sprite follows finger position (mobile). | — |
| 'drag' | Click/tap and hold to drag the sprite. Release to stop. | — |
| 'keyboard' | Arrow keys or WASD move the sprite at a constant speed. | keyboardSpeed |
| 'scroll' | Mouse wheel input moves the sprite in 2D. | scrollSpeed |
| 'click' | Click/tap anywhere to animate the sprite to that point. | — |
| 'gyro' | Device tilt (accelerometer) moves the sprite. iOS requires a permission dialog. | gyroSensitivity |
| 'gamepad' | Left stick on a connected gamepad. Auto-detects connection. | gamepadDeadzone |
| 'pointer' | Unified pointer events — covers mouse, touch, and pen in one binding. | — |
// Common cross-device pattern movementTypes: ['mouse', 'touch'] // Keyboard movement with tuned speed movementTypes: ['keyboard'], keyboardSpeed: 8 // Puzzle — deliberate drag only movementTypes: ['drag'] // Gyro on mobile with mouse fallback movementTypes: ['gyro', 'mouse'], gyroSensitivity: 8
Interaction Types
Define what action completes the ad. When any interaction triggers, triggerCompletion() fires automatically. For zone-only completion, set this to an empty array and use landingZones instead.
config.interactionTypes[]
| Value | Behavior | Tuning property |
|---|---|---|
| 'click' | Single click anywhere in the container. | — |
| 'doubleClick' | Double-click to complete. | — |
| 'rightClick' | Right-click / context menu. | — |
| 'tap' | Single tap (touch). | — |
| 'doubleTap' | Double-tap. | doubleTapDelay |
| 'longPress' | Press and hold. | longPressDuration |
| 'swipe' | Swipe in any direction. Emits direction in event data. | swipeThreshold |
| 'keyPress' | Press Space or Enter. | — |
| 'shake' | Shake the device. iOS requires permission. | shakeThreshold |
| 'hover' | Hover over the container for a set duration. | hoverDuration |
interactionTypes: [] combined with landingZones and autoCompleteOnZone: true. The ad will only complete when the sprite physically reaches a target zone — great for drag-to-reveal, puzzle, and path-finding experiences.Landing Zones
Target areas inside the container. When the sprite enters a zone (and autoCompleteOnZone is true), the ad completes or routes to a segment. Three zone shapes are available, and each zone can carry its own completion media, transition, and callbacks.
config.landingZones[]
Zone Shapes
landingZones: [ // Rectangle — axis-aligned bounding box { type: 'rect', x: '70%', y: '60%', width: '20%', height: '30%' }, // Circle — center point + radius { type: 'circle', x: '50%', y: '50%', radius: '15%' }, // Polygon — arbitrary vertices, ray-casting collision { type: 'polygon', points: [ { x: '60%', y: '20%' }, { x: '90%', y: '50%' }, { x: '60%', y: '80%' } ]} ]
Zone Properties
config.landingZones[n].*
| Property | Type | Description |
|---|---|---|
| type | string | 'rect' (default), 'circle', or 'polygon'. |
| x, y | number|string | Position — top-left corner for rect, center for circle. Accepts px or '50%'. |
| width, height | number|string | Rect dimensions. Default: 80px each. |
| radius | number|string | Circle radius. Default: 40px. |
| points | Array | Polygon vertices: [{ x, y }, ...]. Minimum 3 points. |
| id | string | Optional identifier for your own use. It stays on the zone object that getLandingZones() returns. |
| segmentIndex | number | Jump to this segment on zone entry instead of advancing sequentially. See Zone Routing. |
| completion | string | Override the completion media URL for this zone only. |
| completionTransition | string | Override the transition for this zone only (e.g. 'confetti'). |
| transitionDuration | number | Override the transition duration (ms) for this zone only. |
| onEnter | function | Callback when sprite enters this zone: ({ zone, x, y, instance }) => {}. |
Zone Routing
By default, all zones trigger the same completion. Zone routing lets each zone jump to a specific segment or display unique completion media — enabling branching experiences like "choose your path", poll-style reveals, and A/B product picks.
Route to different segments — set segmentIndex on a zone to jump directly to that segment:
landingZones: [ { type: 'circle', id: 'left', x: '25%', y: '60%', radius: '12%', segmentIndex: 1 }, { type: 'circle', id: 'right', x: '75%', y: '60%', radius: '12%', segmentIndex: 2 } ]
Zone-specific completions — each zone shows its own completion image, no segments needed:
landingZones: [ { id: 'yes', type: 'rect', x: '10%', y: '60%', width: '35%', height: '30%', completion: 'yes-reveal.png', completionTransition: 'confetti' }, { id: 'no', type: 'rect', x: '55%', y: '60%', width: '35%', height: '30%', completion: 'no-thanks.png', completionTransition: 'fade' } ]
Zone enter callbacks — run your own logic (badge updates, a callback to your own tools, sound) when the sprite enters a goal:
{ type: 'circle', id: 'goal', x: '80%', y: '50%', radius: '10%',
onEnter: (e) => {
console.log('Hit zone:', e.zone.id);
e.instance.updateBadge('Nice!');
}
}Completion Transitions
The visual effect that plays when showing the completion media. Set globally via completionTransition, per-segment, or per-zone.
config.completionTransition
| Value | Effect |
|---|---|
| 'fade' | Smooth crossfade between states. Works with both images and video. |
| 'zoom' | Completion image zooms in from center with a scale animation. |
| 'confetti' | Burst of colorful particles, then fade to completion. Good for a celebratory reveal. |
| 'flash' | Quick white flash, then reveal. |
| 'spin' | Sprite spins and shrinks out, then completion fades in. |
| 'slide-left' | Completion slides in from the right. |
| 'slide-right' | Completion slides in from the left. |
| 'slide-up' | Completion slides up from the bottom. |
| 'slide-down' | Completion slides down from the top. |
// Global transition completionTransition: 'confetti', transitionDuration: 1200 // Per-zone override landingZones: [{ ..., completionTransition: 'zoom', transitionDuration: 500 }]
Borders
config.borderStyle
| Value | Effect |
|---|---|
| 'solid' | Solid border with subtle box shadow. |
| 'gradient' | 45° gradient from the border color to a lighter variant. |
| 'neon' | Glowing border with pulsing box-shadow animation. |
| 'curtain' | Solid with inset shadow creating a curtain/stage effect. |
| 'frame' | Double border with outline — classic picture frame. |
| 'modern' | Angled clip-path corners for a futuristic look. |
| 'arcade' | Rounded with inset glow, like a retro cabinet. |
| 'scifi' | Thin border + outline + glow — sci-fi HUD aesthetic. |
borderStyle: 'neon', borderColor: '#22c55e', borderWidth: 3
Badge
A floating text label overlaying the ad. Useful for instructions ("Drag →"), hints, scores, or status. Auto-truncates text that would overflow the container. Can be shown, hidden, updated, or removed at any time via the Badge API.
config.badge.*
| Property | Type | Default | Description |
|---|---|---|---|
| text | string | '' | Text content of the badge. |
| position | string | 'top-right' | One of 9 positions (see below). |
| color | string | '#4a90e2' | Badge background color. |
| textColor | string | '#fff' | Text color. |
| fontSize | number | 14 | Font size in px. |
| padding | number | 10 | Inner padding in px. |
| borderRadius | number | 8 | Corner radius in px. |
| opacity | number | 0.9 | CSS opacity (0–1). |
Positions: top-left, top-center, top-right, center-left, center, center-right, bottom-left, bottom-center, bottom-right.
badge: { text: 'Drag the logo to the box!', position: 'bottom-center', color: 'rgba(0,0,0,0.7)', textColor: '#fff', fontSize: 13, borderRadius: 20 }
Segments
Segments turn an ad into a multi-level experience. Each segment can override almost any config property — media, zones, movement, interactions, border, and transition. When the user completes a segment, the next one loads automatically (or a zone segmentIndex can jump to any segment).
config.segments[]
| Segment property | Description |
|---|---|
| media | Merged with current media. Override background, sprite, completion, etc. |
| movementTypes | Replace movement types for this segment. |
| interactionTypes | Replace interaction types for this segment. |
| landingZones | Replace landing zones for this segment. Zones can include routing properties. |
| autoCompleteOnZone | Override auto-complete behavior. |
| completionTransition | Override transition for this segment. |
| transitionDuration | Override transition duration. |
| borderStyle / borderColor | Override border for this segment. |
segments: [ { // Level 1: drag the sprite to a zone media: { background: 'level1-bg.png' }, landingZones: [{ type: 'circle', x: '75%', y: '80%', radius: '10%' }], movementTypes: ['drag'] }, { // Level 2: tap to reveal the final offer media: { background: 'level2-bg.png', completion: 'offer.png' }, interactionTypes: ['click', 'tap'], completionTransition: 'confetti' } ], onSegmentComplete: (idx, seg) => { console.log('Completed segment', idx); }
Frustration Detection
Automatically detects when a user is struggling and escalates through a series of interventions. The system tracks: idle time, total time, rapid clicks, rage taps, erratic movement patterns, edge bumps, backtracking, and device shakes. Each signal contributes a weighted score, and configurable thresholds trigger escalating actions.
config.frustration.*
| Property | Type | Default | Description |
|---|---|---|---|
| enabled | boolean | false | Turn on frustration tracking. |
| sensitivity | number | 5 | Range 1 (very lenient) to 10 (triggers quickly). Controls threshold scaling. |
| escalation | Object[] | see below | Array of { score, action } thresholds. Actions fire when the frustration score reaches each threshold. |
| hintText | string | 'Try moving toward the highlighted area!' | Toast text for the 'hint' action. |
| instructionTitle | string | 'Need Help?' | Modal title for the 'instruction' action. |
| instructionMessage | string | 'Move the cursor/sprite to the target area to complete the level.' | Modal body text. |
| autoSolveDelay | number | 1000 | Ms before auto-solve animation begins. |
| cooldownPeriod | number | 10000 | Minimum ms between consecutive escalation actions. |
Escalation actions (in typical order of severity):
'hint'— A floating toast message with custom text.'instruction'— A modal dialog with title, message, and a Skip Level button.'highlight'— Pulsing glow animation around all landing zones.'guide'— Moves the sprite halfway toward the first landing zone.'autoSolve'— Sprite automatically navigates to the first landing zone and completes the current level.
frustration: { enabled: true, sensitivity: 6, escalation: [ { score: 25, action: 'hint' }, { score: 50, action: 'instruction' }, { score: 75, action: 'highlight' }, { score: 95, action: 'autoSolve' } ], hintText: 'Almost there — try the glowing area!', cooldownPeriod: 8000 }
Audio Control
Adds a mute/unmute toggle button to video ads. The button auto-attaches to background videos, sprite videos, and completion videos. Renders as a floating circular icon inside the container.
config.audioControl.*
| Property | Type | Default | Description |
|---|---|---|---|
| enabled | boolean | true | Show the audio control button. |
| position | string | 'bottom-right' | Button position: top-left, top-right, bottom-left, bottom-right, center. |
| size | number | 40 | Button diameter in px. |
| color | string | '#fff' | Icon/emoji color. |
| backgroundColor | string | 'rgba(0,0,0,0.6)' | Button background. |
| hoverColor | string | '#4a90e2' | Background on hover. |
| muteLabel | string | 'Mute' | aria-label when audio is on. |
| unmuteLabel | string | 'Unmute' | aria-label when audio is off. |
audioControl: { enabled: true, position: 'top-right', size: 32 }
Auto Resize
config.autoResize
When true, Adium attaches a ResizeObserver to the container. On every resize, it re-resolves all percentage-based sprite sizes and landing zone coordinates against the new container dimensions. Use percentages throughout for ads that adapt to any container size — desktop sidebars, mobile full-bleed, responsive iframes, etc.
autoResize: true, media: { sprite: { image: 'icon.png', size: { width: '10%', height: '10%' } } }, landingZones: [{ type: 'circle', x: '80%', y: '80%', radius: '8%' }]
Accepted size units: 48 (pixels), '50%' (percentage of container), '10vw' / '10vh' (viewport), 'auto' (natural image size).
Event Bus
Subscribe to lifecycle and interaction events dynamically. Unlike config callbacks, you can add/remove multiple listeners at any time, and all methods return the instance for chaining.
| Event | Payload | When |
|---|---|---|
| 'ready' | { instanceId } | Init complete, assets loaded, interactive. |
| 'impression' | { instanceId, timestamp, platform } | Fires once, when init completes. With lazyInit, when at least 10% of the box is visible. |
| 'engagement' | { instanceId, interactionType, timeToEngage, platform } | First user interaction (fires once). |
| 'interaction' | { type, data, timestamp } | Every interaction event (click, swipe, etc.). |
| 'segmentComplete' | { instanceId, index, segment, total } | A level finished. Emitted once per finished level (not for the last level, which emits complete), before the next level loads. |
| 'complete' | { instanceId, timestamp, timeToComplete, skipped } | The last level finished. Payload includes skipped (boolean). |
| 'ended' | { type, instanceId } | A non-looping background or completion video finished playing. type is 'background' or 'completion'. |
| 'frustration' | { score, action, reasons } | Frustration escalation triggered. |
| 'destroy' | { instanceId } | Instance fully torn down. |
Forward events to your own tools. Adium does not send them itself.
ad.on('impression', (e) => host.track('impression', e)) .on('engagement', (e) => host.track('engagement', { type: e.interactionType })) .on('complete', (e) => host.track('complete', { ms: e.timeToComplete }));
Viewable events, and the second callback argument
The 'viewable' event lets your page count viewability itself. Adium only loads the media URLs you provide. It sends no data to Adium or anyone else, and it does not talk to your queue provider or your other tools. Every listener also receives a second argument, meta: { event, seq, timestamp, segmentIndex } (seq counts the instance's emits, segmentIndex is null without segments). The full contract is in docs/events.md in the repository.
| Event | Payload | When |
|---|---|---|
| 'viewable' | { instanceId, timestamp, timeToViewable, threshold, durationMs, intersectionRatio, platform } | Once per instance, after 'impression': at least viewability.threshold (default 50%) of the container's pixels have been in view for viewability.durationMs (default 1 s) continuously, with the page visible. Nothing is observed unless you set config.viewability or config.onViewable, or call ad.on('viewable', fn). Needs IntersectionObserver. |
ad.on('viewable', (e, meta) => host.track('viewable', { ms: e.timeToViewable, seq: meta.seq }));
Core Methods
loadSegment(0).cfg after construct: the instance keeps its own deep copy of plain nested objects/arrays (ad.config !== cfg), so a post-construct write on cfg (top-level or nested) is not seen by the engine.'destroy'.{ x, y } — the sprite's current pixel coordinates relative to the container's top-left corner.autoCompleteOnZone is true and the sprite moves into a zone from outside it, triggers completion.300ms. Each frame calls moveSprite(), so zone collision is checked throughout the animation.'2.1.0'). Also available as Adium.getVersion().ad.config, which is itself a deep clone of the host's plain nested objects/arrays made at construct; functions and DOM nodes stay by reference)."Adium v2.1.0 [adium-abc123] (desktop/chrome)".{ duration, easing, delay, iterations, fillMode, onComplete }.{ count, colors, duration, origin: { x, y } }.Movement & Interaction API
Dynamically change how the sprite moves and what triggers completion — after initialization.
// Dynamically change controls between segments ad.on('segmentComplete', (e) => { if (e.index === 0) { ad.setMovementTypes(['keyboard']); ad.setInteractionTypes([]); // zone-only for level 2 } });
Segment Methods
false if there are no more segments (final segment reached).null if no segments are defined.{ current, total, percentage }. Example: { current: 2, total: 3, percentage: 67 }.Zone Methods
segmentIndex, completion, and onEnter.boolean.// Add a bonus zone at runtime ad.addLandingZone({ type: 'circle', id: 'bonus', x: '90%', y: '10%', radius: '5%', completion: 'bonus-reveal.png', completionTransition: 'confetti' }); ad.showLandingZones(); // visualize all zones // Check collision manually const pos = ad.getSpritePosition(); if (ad.isInLandingZone(pos.x, pos.y)) console.log('Sprite is inside a zone');
Badge Methods
updateBadge().Platform Detection
Adium auto-detects device type, browser, OS, and hardware capabilities on init. These methods let you adapt behavior or run conditional code for different platforms.
{ browser, browserVersion, os, deviceType, features, screen, userAgent }.'desktop', 'mobile', 'tablet'. Returns boolean.'chrome', 'safari', 'firefox', 'edge', 'opera', 'samsung'.'windows', 'macos', 'linux', 'ios', 'android'.'touch', 'pointer', 'deviceOrientation', 'deviceMotion', 'gamepad', 'fullscreen', 'vibration'.'mobile-safari'. Multiple matching keys all execute.ad.runPlatformCode({ mobile: () => ad.setMovementTypes(['touch']), desktop: () => ad.setMovementTypes(['mouse']), safari: () => { /* iOS Safari workaround */ } }); // Also available as a config property: // Handlers run with this = the instance and receive the platform info as their first argument platformOverrides: { mobile: function () { this.setMovementTypes(['touch']); }, desktop: function (platform) { this.setMovementTypes(['mouse', 'keyboard']); } }
Color Extraction
Extract dominant colors from images for dynamic theming, auto-matching backgrounds, and generating accessible text colors. All color methods are async (return Promises) since they analyze image pixel data via canvas.
{ dominant, palette, vibrant, muted, light, dark }. Each entry has { rgb, hex, count }. Options: { sampleSize, quality, excludeWhite, excludeBlack }.'#3b82f6'.{ r, g, b }.'#000000' or '#ffffff' based on the luminance of the input — ensures readable text on any background.Lifecycle & Permissions
true if critical assets loaded and init() completed.true if all assets (including lazy/deferred) finished loading.preloadMode. After destroy() it resolves immediately and does nothing; a call already in flight when destroy() runs stays pending (it never resolves or rejects).preloadMode: 'partial'. After destroy() it resolves immediately and does nothing; a call already in flight when destroy() runs stays pending (it never resolves or rejects).'deviceOrientation', 'deviceMotion', 'geolocation', 'notifications'. Options can override title, message, icon.'granted', 'denied', 'error', or null (not requested).Auto-Sizing Utilities
These methods resolve responsive size units to pixel values based on the current container dimensions. Used internally by sprite rendering and zone collision, but also available publicly for custom positioning logic.
'50%' → 50% of referenceDimension. '10vw' → 10% of viewport width. '10vh' → viewport height. Plain numbers pass through. 'auto' (or null/undefined) returns null.{ width, height } config to pixel values using the current container width/height.Static Constants
Access these on the Adium class directly — no instance needed. Useful for referencing valid values without magic strings.
Adium.VERSION // '2.1.0' Adium.EVENTS // { READY, COMPLETE, INTERACTION, SEGMENT_COMPLETE, FRUSTRATION, IMPRESSION, ENGAGEMENT, DESTROY, ENDED } plus non-enumerable VIEWABLE Adium.MOVEMENT_TYPES // { MOUSE, TOUCH, KEYBOARD, DRAG, SCROLL, CLICK, GYRO, GAMEPAD, POINTER } Adium.INTERACTION_TYPES // { CLICK, TAP, DOUBLE_CLICK, DOUBLE_TAP, SWIPE, HOVER, ... } Adium.PRELOAD_MODES // { FULL, PARTIAL, NONE } Adium.PLATFORMS // { DESKTOP, MOBILE, TABLET } Adium.BROWSERS // { CHROME, SAFARI, FIREFOX, EDGE, OPERA, SAMSUNG, IE, UNKNOWN } Adium.OS_TYPES // { WINDOWS, MACOS, LINUX, IOS, ANDROID, UNKNOWN } Adium.ANIMATIONS // { FADE_IN, ZOOM_IN, BOUNCE_IN, SLIDE_IN_UP, CONFETTI, GLITCH, ... } Adium.EASINGS // { LINEAR, EASE, EASE_IN_OUT, EASE_OUT_BACK, SPRING } Adium.FRUSTRATION_LEVELS // { OFF: 0, LOW: 2, MEDIUM: 5, HIGH: 7, INSTANT: 10, ... } Adium.FRUSTRATION_ACTIONS // { NONE, HINT, INSTRUCTION, HIGHLIGHT, GUIDE, AUTO_SOLVE } Adium.FRUSTRATION_THRESHOLDS // Default thresholds for each tracked signal Adium.Z_INDEX // { BACKGROUND: 1, LANDING_ZONE: 10, SPRITE: 100, BADGE: 500, MODAL: 2000, ... } Adium.BRAND // { accent: '#3b82f6', dark: '#0f172a', gradient, card }
Adium Studio Examples
Try a config in the browser with the config builder.
Example: Choose Your Path (Zone Routing)
Two landing zones on an intro screen route to different product segments. The user's choice determines which detail page and completion they see.
new Adium({ target: document.getElementById('ad'), autoResize: true, media: { background: 'choose-bg.png', backgroundSize: 'cover', sprite: { image: 'hand-icon.png', size: { width: '10%', height: '10%' } } }, movementTypes: ['mouse', 'touch'], interactionTypes: [], landingZones: [ { type: 'rect', id: 'sneakers', x: '5%', y: '55%', width: '40%', height: '35%', segmentIndex: 1 }, { type: 'rect', id: 'boots', x: '55%', y: '55%', width: '40%', height: '35%', segmentIndex: 2 } ], autoCompleteOnZone: true, segments: [ {}, // segment 0: choice screen { media: { background: 'sneaker-detail.png', completion: 'sneaker-cta.png' }, interactionTypes: ['click', 'tap'], completionTransition: 'confetti' }, { media: { background: 'boots-detail.png', completion: 'boots-cta.png' }, interactionTypes: ['click', 'tap'], completionTransition: 'zoom' } ], badge: { text: 'Drag to choose', position: 'top-center' }, onComplete: (zone) => { if (zone) analytics.track('choice', { picked: zone.id }); } });
Example: Zone-Specific Completions (No Segments)
Three answer zones on a poll ad. Each zone displays its own completion image with a different transition — no segments required.
new Adium({ target: document.getElementById('ad'), media: { background: 'poll-question.png', sprite: { image: 'pointer.png', size: { width: 40, height: 40 } } }, movementTypes: ['mouse', 'touch'], interactionTypes: [], autoCompleteOnZone: true, landingZones: [ { id: 'a', type: 'rect', x: '5%', y: '60%', width: '28%', height: '30%', completion: 'result-a.png', completionTransition: 'fade' }, { id: 'b', type: 'rect', x: '36%', y: '60%', width: '28%', height: '30%', completion: 'result-b.png', completionTransition: 'zoom' }, { id: 'c', type: 'rect', x: '67%', y: '60%', width: '28%', height: '30%', completion: 'result-c.png', completionTransition: 'confetti' } ] });
Example: Video Ad with Progress Bar
Video background with a progress bar, audio toggle, and a video completion with its own countdown progress bar.
new Adium({ target: document.getElementById('ad'), media: { background: 'hero.mp4', videoLoop: false, videoMuted: false, videoProgressBar: { height: 4, color: '#f1c40f' }, sprite: { image: 'play.png', size: { width: 64, height: 64 } }, completion: 'reveal.mp4', completionVideoLoop: false, completionVideoMuted: false, completionVideoProgressBar: { color: '#22c55e', direction: 'countdown' } }, audioControl: { position: 'bottom-right' }, movementTypes: ['mouse', 'touch'], interactionTypes: ['click'], completionTransition: 'fade', onVideoComplete: (e) => console.log(e.type + ' video ended') });
Example: Forward events to your own tools
Chain listeners and forward each event to your own tools. Adium does not include built-in reporting and does not send these events itself.
const ad = new Adium({ /* config */ }); ad.on('impression', (e) => host.track('impression', { id: e.instanceId })) .on('engagement', (e) => host.track('engagement', { type: e.interactionType, ms: e.timeToEngage })) .on('frustration',(e) => host.track('frustration', { score: e.score, action: e.action })) .on('complete', (e) => host.track('complete', { ms: e.timeToComplete }));
Example: Multi-segment moment with frustration detection
A three-level moment: keyboard controls on level 1, drag on level 2, tap-to-finish on level 3. Frustration detection helps stuck players with escalating hints.
new Adium({ target: document.getElementById('ad'), autoResize: true, media: { background: 'level1-bg.png', backgroundSize: 'cover', sprite: { image: 'character.png', size: { width: '12%', height: '12%' } } }, movementTypes: ['keyboard'], interactionTypes: [], autoCompleteOnZone: true, segments: [ { // Level 1: navigate to the circle landingZones: [{ type: 'circle', x: '85%', y: '80%', radius: '8%' }], borderStyle: 'arcade', borderColor: '#3b82f6' }, { // Level 2: drag to the rect media: { background: 'level2-bg.png' }, movementTypes: ['drag'], landingZones: [{ type: 'rect', x: '65%', y: '10%', width: '25%', height: '25%' }], borderStyle: 'neon', borderColor: '#f59e0b' }, { // Level 3: tap to claim media: { background: 'level3-bg.png', completion: 'victory.png' }, interactionTypes: ['click', 'tap'], completionTransition: 'confetti', borderStyle: 'scifi', borderColor: '#22c55e' } ], frustration: { enabled: true, sensitivity: 4, escalation: [ { score: 30, action: 'hint' }, { score: 60, action: 'highlight' }, { score: 90, action: 'autoSolve' } ], hintText: 'Try the glowing area!' }, badge: { text: 'Level 1', position: 'top-left' }, onSegmentComplete: (idx) => { ad.updateBadge('Level ' + (idx + 2)); }, debug: true });
A couple of questions
- Who brings the sponsor?
- You do. Adium has no ad network; you can add a sponsor message in that space.