See the demos

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:

  1. Preload — Assets load based on preloadMode (full, partial, or none). A branded spinner and loading text display while images and video buffer. If lazyInit is set, loading starts when at least 10% of the box is visible (IntersectionObserver threshold 0.1).
  2. Init — Background applied, sprite created and centered, movement and interaction listeners bound, border and badge rendered. The ready event fires and onReady callback runs. The instance is now interactive.
  3. Interaction — The user moves the sprite and/or triggers a completion interaction. Every interaction emits an interaction event. The first interaction also fires engagement (once). If frustration detection is enabled, the system begins scoring user behavior for signs of confusion.
  4. Completion — Transition plays (fade, confetti, zoom, etc.), completion media replaces the background, onComplete fires. If segments are defined, the next segment loads instead of completing. If the triggering zone has a segmentIndex or its own completion, those are used instead of the defaults.
No completion media? If you omit 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.

config = {
  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.*

PropertyTypeDescription
targetElementRequired. The DOM element Adium renders into. Must have explicit width and height (inline style, CSS class, or parent constraint).
mediaObjectRequired. All visual assets — background, sprite, completion. See Media & Assets.
movementTypesstring[]How the sprite moves: 'mouse', 'touch', 'drag', etc. Default: []. See Movement Types.
interactionTypesstring[]What triggers completion: 'click', 'tap', 'swipe', etc. Default: []. See Interaction Types.
landingZonesObject[]Target areas for zone-based completion. Default: []. See Landing Zones.
autoCompleteOnZonebooleanAuto-complete when sprite enters a landing zone. Default: true.
completionTransitionstringTransition effect when showing completion. See Transitions.
transitionDurationnumberTransition time in ms. Default: 1000.
borderStylestringDecorative border around the container. See Borders.
borderColorstringBorder color. Use 'auto' to detect from parent. Default: brand blue.
borderWidthnumberBorder thickness in px. Default: 10.
badgeObjectFloating text label overlay. See Badge.
segmentsObject[]Multi-level experience. See Segments.
frustrationObjectFrustration detection system. See Frustration Detection.
audioControlObjectAudio mute/unmute button for video ads. See Audio Control.
preloadModestring'full' (all assets), 'partial' (critical only, default), or 'none' (lazy load everything).
autoResizebooleanRe-resolve %-based sizes on container resize via ResizeObserver. Default: false. See Auto Resize.
lazyInitbooleanDelay initialization until at least 10% of the box is visible (IntersectionObserver threshold 0.1). Default: false.
viewabilityObjectOptional. { 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.
debugbooleanEnable verbose console logging for all internal events. Default: false.
platformOverridesObjectPlatform-specific code blocks. Keys: desktop, mobile, tablet, chrome, safari, ios, etc. See Platform Detection.
keyboardSpeednumberPx per frame for keyboard movement. Default: 5.
scrollSpeednumberMouse wheel movement multiplier. Default: 2.
gyroSensitivitynumberDevice tilt movement multiplier. Default: 5.
gamepadDeadzonenumberGamepad stick deadzone (0–1). Default: 0.15.
hoverDurationnumberMilliseconds of hover required to trigger completion. Default: 1000.
longPressDurationnumberMilliseconds to hold for longPress interaction. Default: 500.
swipeThresholdnumberPixel distance to register a swipe. Default: 50.
doubleTapDelaynumberMax ms between taps for doubleTap. Default: 300.
shakeThresholdnumberAccelerometer delta to trigger shake. Default: 15.
loadingTextstringText shown on the loading screen spinner. Default: "Loading...".
loadingBackgroundstringLoading screen background color. Default: Adium brand dark (#0f172a).
autoMatchBackgroundbooleanAuto-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.*

PropertySignatureWhen it fires
onComplete(payload) => voidAd 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) => voidA 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) => voidInit finished, assets loaded, ready for interaction. Receives the Adium instance.
onInteraction(type, data) => voidEvery interaction event (click, swipe, hover, etc.). type is the interaction name, data contains coordinates or direction.
onImpression({instanceId}) => voidFires 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}) => voidFirst meaningful user interaction (fires once). timeToEngage is milliseconds since impression.
onViewable(payload) => voidThe container became viewable (fires once). Same payload as the 'viewable' event.
onVideoComplete({type, video}) => voidA non-looping video finishes playing. type is 'background' or 'completion'. video is the HTMLVideoElement.
onPermissionRequest(type, config) => voidBefore a permission dialog is shown. type is 'deviceOrientation', 'deviceMotion', etc.
onPermissionGranted(type) => voidA browser permission was granted.
onPermissionDenied(type, reason) => voidA browser permission was denied or errored.
Callbacks vs Events: Callbacks are set once in the config at init time. The event bus (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.*

PropertyTypeDescription
backgroundstringURL of background image or video. Fills the container. For video, it auto-plays muted by default.
backgroundSizestring'cover' (fills, may crop — default), 'contain' (fits, may letterbox), 'stretch' (exact fill, may distort), or 'auto' (natural size).
backgroundColorstringFallback CSS color behind the background. Visible during loading or around contained images.
completionstringURL of completion image or video. Shown after the user completes the ad. Optional — if omitted, the sprite hides and the background stays.
videoLoopbooleanLoop the background video. Default: true.
videoMutedbooleanMute the background video. Default: true. Set false with audioControl for sound-on experiences.
completionVideoLoopbooleanLoop the completion video. Default: true.
completionVideoMutedbooleanMute 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.*

PropertyTypeDescription
imagestringURL of sprite image or video file.
sizeObject{ width, height } — accepts px numbers (48), percentage strings ('15%'), viewport units ('10vw'), or 'auto'.
videoProgressBarObjectProgress 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.*

PropertyTypeDefaultDescription
enabledbooleantrueShow the progress bar.
heightnumber5Bar height in px.
colorstring'#4a90e2'Fill color of the progress bar.
backgroundColorstring'rgba(0,0,0,0.5)'Track background color.
directionstring'normal''normal' fills left→right. 'countdown' shrinks right→left (great for time-remaining).
positionstring'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[]

ValueBehaviorTuning 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[]

ValueBehaviorTuning 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
Zone-only completion: Set 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].*

PropertyTypeDescription
typestring'rect' (default), 'circle', or 'polygon'.
x, ynumber|stringPosition — top-left corner for rect, center for circle. Accepts px or '50%'.
width, heightnumber|stringRect dimensions. Default: 80px each.
radiusnumber|stringCircle radius. Default: 40px.
pointsArrayPolygon vertices: [{ x, y }, ...]. Minimum 3 points.
idstringOptional identifier for your own use. It stays on the zone object that getLandingZones() returns.
segmentIndexnumberJump to this segment on zone entry instead of advancing sequentially. See Zone Routing.
completionstringOverride the completion media URL for this zone only.
completionTransitionstringOverride the transition for this zone only (e.g. 'confetti').
transitionDurationnumberOverride the transition duration (ms) for this zone only.
onEnterfunctionCallback 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

ValueEffect
'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

ValueEffect
'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.*

PropertyTypeDefaultDescription
textstring''Text content of the badge.
positionstring'top-right'One of 9 positions (see below).
colorstring'#4a90e2'Badge background color.
textColorstring'#fff'Text color.
fontSizenumber14Font size in px.
paddingnumber10Inner padding in px.
borderRadiusnumber8Corner radius in px.
opacitynumber0.9CSS 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 propertyDescription
mediaMerged with current media. Override background, sprite, completion, etc.
movementTypesReplace movement types for this segment.
interactionTypesReplace interaction types for this segment.
landingZonesReplace landing zones for this segment. Zones can include routing properties.
autoCompleteOnZoneOverride auto-complete behavior.
completionTransitionOverride transition for this segment.
transitionDurationOverride transition duration.
borderStyle / borderColorOverride 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.*

PropertyTypeDefaultDescription
enabledbooleanfalseTurn on frustration tracking.
sensitivitynumber5Range 1 (very lenient) to 10 (triggers quickly). Controls threshold scaling.
escalationObject[]see belowArray of { score, action } thresholds. Actions fire when the frustration score reaches each threshold.
hintTextstring'Try moving toward the highlighted area!'Toast text for the 'hint' action.
instructionTitlestring'Need Help?'Modal title for the 'instruction' action.
instructionMessagestring'Move the cursor/sprite to the target area to complete the level.'Modal body text.
autoSolveDelaynumber1000Ms before auto-solve animation begins.
cooldownPeriodnumber10000Minimum ms between consecutive escalation actions.

Escalation actions (in typical order of severity):

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.*

PropertyTypeDefaultDescription
enabledbooleantrueShow the audio control button.
positionstring'bottom-right'Button position: top-left, top-right, bottom-left, bottom-right, center.
sizenumber40Button diameter in px.
colorstring'#fff'Icon/emoji color.
backgroundColorstring'rgba(0,0,0,0.6)'Button background.
hoverColorstring'#4a90e2'Background on hover.
muteLabelstring'Mute'aria-label when audio is on.
unmuteLabelstring'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.

ad.on(event, callback)
Subscribe to an event. Returns the Adium instance for chaining.
ad.off(event, callback?)
Unsubscribe a specific callback, or omit callback to remove all listeners for that event.
EventPayloadWhen
'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.

EventPayloadWhen
'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

ad.triggerCompletion()
Programmatically trigger completion. Takes no arguments: advances to the next segment, or shows the completion on the last one. A repeat call during the same level is ignored.
ad.resetLevel()
Reset to the initial interactive state: restores background, re-centers sprite, re-binds all listeners, resets frustration metrics and zone tracking. In a multi-level moment it rewinds to level 1, like loadSegment(0).
ad.updateConfig(newConfig)
Merge new properties into the current config and re-apply. Useful for changing movement types, media, or interactions dynamically after init. Prefer this over writing keys on the host's original 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.
ad.destroy()
Full teardown: removes all event listeners, ResizeObserver, IntersectionObserver, DOM elements (sprite, badge, borders, audio controls, progress bars), and emits 'destroy'.
ad.getSpritePosition()
Returns { x, y } — the sprite's current pixel coordinates relative to the container's top-left corner.
ad.moveSprite(x, y)
Instantly move the sprite to absolute pixel coordinates. If autoCompleteOnZone is true and the sprite moves into a zone from outside it, triggers completion.
ad.animateSpriteTo(x, y, duration?)
Smoothly animate the sprite to a target point using ease-out cubic easing. Default duration: 300ms. Each frame calls moveSprite(), so zone collision is checked throughout the animation.
ad.getVersion()
Returns the library version string ('2.1.0'). Also available as Adium.getVersion().
ad.getConfig()
Returns a shallow copy of the current config object (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).
ad.toJSON()
Returns a serializable snapshot: version, platform, browser, frustration score, segment progress, movement types, etc. Useful for logging and debugging.
ad.toString()
Returns a human-readable description, e.g. "Adium v2.1.0 [adium-abc123] (desktop/chrome)".
ad.animate(element, animation, options?)
Apply a CSS keyframe animation to any DOM element. Options: { duration, easing, delay, iterations, fillMode, onComplete }.
ad.createConfetti(options?)
Burst of confetti particles inside the container. Options: { count, colors, duration, origin: { x, y } }.

Movement & Interaction API

Dynamically change how the sprite moves and what triggers completion — after initialization.

ad.setMovementTypes(types)
Replace all movement types. Accepts a single string or array. Tears down old listeners and binds new ones.
ad.addMovementType(type)
Add a movement type without removing existing ones.
ad.removeMovementType(type)
Remove a single movement type and unbind its listeners.
ad.setInteractionTypes(types)
Replace all interaction types. Accepts a single string or array.
ad.addInteractionType(type)
Add an interaction type.
ad.removeInteractionType(type)
Remove an interaction type.
// 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

ad.loadSegment(index)
Jump to a specific segment by 0-based index. Cleans up the current segment (removes sprite, video, listeners) and applies the new segment's config overrides. Also resets frustration metrics and zone tracking state.
ad.nextSegment()
Advance to the next segment in order. Returns false if there are no more segments (final segment reached).
ad.getCurrentSegment()
Returns the current segment config object, or null if no segments are defined.
ad.getSegmentProgress()
Returns { current, total, percentage }. Example: { current: 2, total: 3, percentage: 67 }.

Zone Methods

ad.addLandingZone(zone)
Add a new landing zone at runtime. The zone object uses the same shape as config.landingZones[n], including routing properties like segmentIndex, completion, and onEnter.
ad.clearLandingZones()
Remove all landing zones.
ad.getLandingZones()
Returns the array of current landing zone config objects (the raw configs you defined, including percentages).
ad.getResolvedZones()
Returns landing zones with all coordinates resolved to current pixel values (percentages computed against current container size).
ad.isInLandingZone(x, y)
Check if a pixel coordinate is inside any zone. Returns boolean.
ad.showLandingZones()
Render dashed blue debug outlines on rect and circle zones (polygon zones are not drawn). Helpful during development.
ad.hideLandingZones()
Remove the debug outlines.
// 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

ad.updateBadge(text)
Update the badge text. Creates the badge DOM element if it doesn't exist yet.
ad.setBadgeText(text)
Alias for updateBadge().
ad.showBadge()
Fade the badge to visible (opacity transition).
ad.hideBadge()
Fade the badge to invisible (opacity 0).
ad.removeBadge()
Completely remove the badge element from the DOM.

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.

ad.detectPlatform()
Re-runs platform detection and returns the full platform object.
ad.getPlatform()
Returns the cached platform info: { browser, browserVersion, os, deviceType, features, screen, userAgent }.
ad.isPlatform(type)
Check device type: 'desktop', 'mobile', 'tablet'. Returns boolean.
ad.isBrowser(type)
Check browser: 'chrome', 'safari', 'firefox', 'edge', 'opera', 'samsung'.
ad.isOS(type)
Check OS: 'windows', 'macos', 'linux', 'ios', 'android'.
ad.hasFeature(feature)
Check hardware features: 'touch', 'pointer', 'deviceOrientation', 'deviceMotion', 'gamepad', 'fullscreen', 'vibration'.
ad.runPlatformCode(handlers)
Execute platform-specific functions. Keys can be device types, browsers, OS names, or combos like '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.

await ad.extractColors(imageUrl, options?)
Analyze an image and return { dominant, palette, vibrant, muted, light, dark }. Each entry has { rgb, hex, count }. Options: { sampleSize, quality, excludeWhite, excludeBlack }.
await ad.matchBackgroundColor(imageUrl)
Extract the dominant color from an image and set it as the container's CSS background-color. Eliminates letterbox gaps around contained background images.
await ad.getMediaColors()
Extract colors from all configured media (background, sprite, completion) and return them grouped by source.
ad.rgbToHex(r, g, b)
Convert RGB values (0–255) to a hex string like '#3b82f6'.
ad.hexToRgb(hex)
Convert a hex string to { r, g, b }.
ad.getContrastingTextColor(hex)
Returns '#000000' or '#ffffff' based on the luminance of the input — ensures readable text on any background.

Lifecycle & Permissions

ad.onReady(callback)
Register a ready callback. Fires immediately if already ready. Multiple callbacks can be queued before init completes.
ad.isReady()
Returns true if critical assets loaded and init() completed.
ad.isFullyLoaded()
Returns true if all assets (including lazy/deferred) finished loading.
await ad.waitForReady(callback?)
Returns a Promise that resolves when ready. Optional callback also fires.
ad.preloadAllAssets()
Force-preload all media (background, sprite, completion) regardless of preloadMode. After destroy() it resolves immediately and does nothing; a call already in flight when destroy() runs stays pending (it never resolves or rejects).
ad.preloadCriticalAssets()
Preload only background and sprite (not completion). This is the default for 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).
await ad.requestPermission(type, options?)
Show a branded permission dialog, then request the browser API. Types: 'deviceOrientation', 'deviceMotion', 'geolocation', 'notifications'. Options can override title, message, icon.
ad.getPermissionState(type)
Returns '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.

ad.resolveSize(value, referenceDimension)
Resolve any size value to pixels. '50%' → 50% of referenceDimension. '10vw' → 10% of viewport width. '10vh' → viewport height. Plain numbers pass through. 'auto' (or null/undefined) returns null.
ad.resolveSpriteSize(sizeConfig)
Resolve a { width, height } config to pixel values using the current container width/height.
ad.resolveZone(zone)
Resolve a landing zone's coordinates from percentages to pixels. Returns a new zone object with numeric x, y, width, height, radius, and/or points.

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.