Control animated SVGs
An animated molecule export is one self-contained SVG file with one SMIL timeline. It contains no JavaScript and needs no runtime library: the browser plays it. SMIL runs on the standard SVG document timeline, so your page can also script it: pause it, scrub it, or step through it one click at a time.
This page covers molecule animations. LaTeX solution animations are built differently; see LaTeX solution exports.
If you have not exported an animation yet, start with the animation export reference. For the other parts of an export, see the developer overview.
How an animated export is built
Section titled “How an animated export is built”The exporter renders each transition between two consecutive animation states into its own layer group, a g element with a sequential id: <hash>_mk_1, <hash>_mk_2, and so on. The hash comes from the exported content and also names the root (molkit-<hash>), so the same animation exports with the same ids every time, and two different animations on one page never share an id (see Embedding SVGs).
SMIL animate elements crossfade the layers by changing their opacity:
- Each layer fades in when its transition starts and fades out after the next state’s hold ends.
- The crossfade is almost instant, so two layers never show at once.
- With looping enabled at export, every
animatehasrepeatCount="indefinite"; otherwise the timeline plays once and stops on the last frame.
Each transition block has four parts: a hold on the starting state, an optional radical-rotation phase, the transition itself, and a hold on the resulting state. The timing depends on what happens in the step: more travel, more bond changes, and transfers take longer. A state holds until its arrows have finished drawing, plus a short pause. At the default speed, the first state holds for at least 1 second and the last state for at least 2 seconds. Read the times from the root attributes rather than assuming a fixed step length.
The root svg element carries the identity and timing attributes:
<svg id="molkit-0k3j9az" xmlns="http://www.w3.org/2000/svg" viewBox="-43.13 -23.01 86.25 42.32" data-mk-animation="true" data-mk-animation-format="smil" data-mk-animation-states="5" data-duration="5.500" data-breakpoints="0.000,1.200,2.400,3.600,5.500" data-transitions="0.400,1.600,2.800,4.350">| Attribute | Meaning |
|---|---|
data-mk-animation |
true on every animated export. Use it to tell an animation from a static structure SVG. |
data-mk-animation-format |
smil. |
data-mk-animation-states |
Number of states in the timeline. |
data-mk-animation-loop |
true when exported with looping; absent otherwise. |
data-duration |
Total timeline length in seconds. |
data-breakpoints |
Comma-separated times at which each state has fully settled. One entry per state; the first is always 0.000. |
data-transitions |
Comma-separated times at which each transition begins, after the preceding hold and any radical-rotation phase. |
data-mk-effects |
JSON object that records the animation effect options the file was rendered with (for example, color pulse, bond-break fragments, lone-pair and bond morphing, and drift). Present when any options were set. Molkit uses it to restore the same options; its keys are not a stable interface for players. |
Playback methods
Section titled “Playback methods”The playback controls are the standard SMIL methods of every SVGSVGElement, not a Molkit API, so there is nothing to load.
| Call | What it does |
|---|---|
svg.pauseAnimations() |
Stops the timeline at the current time. |
svg.unpauseAnimations() |
Resumes playback. |
svg.animationsPaused() |
Returns true while paused. |
svg.setCurrentTime(t) |
Seeks to t seconds. Works while paused; the frame updates immediately. |
svg.getCurrentTime() |
Current document time in seconds. It only increases: on a looping export it keeps counting past data-duration instead of wrapping. |
You can combine seeking and pausing: pause first, then call setCurrentTime to show any frame as a still.
Choose an embedding method
Section titled “Choose an embedding method”The embedding method decides how much of the playback API you can use:
| Method | Playback | Scripting from your page |
|---|---|---|
img |
Plays, but you cannot pause or seek it | None |
object |
Plays | Only through same-origin contentDocument access |
| Inline | Plays | Full control |
The rest of this page assumes inline embedding. See Embed SVG exports for the full comparison, sizing, and the duplicate-id problem when you inline more than one copy of an export.
Add a play and pause button
Section titled “Add a play and pause button”Start paused, so the reader starts the animation:
const svg = document.querySelector('#stage svg');const btn = document.querySelector('#play-pause');
svg.pauseAnimations(); // start paused on the first frame
btn.addEventListener('click', () => { if (svg.animationsPaused()) { svg.unpauseAnimations(); btn.textContent = 'Pause'; } else { svg.pauseAnimations(); btn.textContent = 'Play'; }});Add a scrubber
Section titled “Add a scrubber”A range input seeks the timeline, and a requestAnimationFrame loop moves the slider while the animation plays.
-
Add a slider next to the inlined SVG:
markup <div id="stage"><!-- inline animated SVG here --></div><input id="scrub" type="range" min="0" step="0.01" value="0"> -
Connect the slider and the timeline in both directions:
scrubber.js const svg = document.querySelector('#stage svg');const scrub = document.querySelector('#scrub');const duration = parseFloat(svg.dataset.duration);scrub.max = duration;// Looping exports use repeatCount="indefinite" on their animationsconst loops = !!svg.querySelector('animate[repeatCount="indefinite"]');let scrubbing = false;scrub.addEventListener('pointerdown', () => {scrubbing = true;svg.pauseAnimations();});scrub.addEventListener('pointerup', () => {scrubbing = false;svg.unpauseAnimations();});scrub.addEventListener('input', () => {svg.setCurrentTime(parseFloat(scrub.value));});// Reflect playback position into the slider.// getCurrentTime() is monotonic, so wrap it for looping exports// and clamp it for one-shot exports.function tick() {if (!scrubbing) {const raw = svg.getCurrentTime();const t = loops ? raw % duration : Math.min(raw, duration);scrub.value = t.toFixed(2);}requestAnimationFrame(tick);}requestAnimationFrame(tick);
Step through states on click
Section titled “Step through states on click”data-breakpoints lists the times at which each state has settled. To step through the states like slides, pause at time zero, then jump from breakpoint to breakpoint on a click or an arrow key:
const svg = document.querySelector('#stage svg');const breakpoints = svg.dataset.breakpoints.split(',').map(Number);let step = 0;
svg.pauseAnimations();svg.setCurrentTime(0);
function goTo(i) { step = Math.max(0, Math.min(i, breakpoints.length - 1)); svg.setCurrentTime(breakpoints[step]);}
svg.addEventListener('click', () => goTo(step + 1));
document.addEventListener('keydown', (e) => { if (e.key === 'ArrowRight') goTo(step + 1); if (e.key === 'ArrowLeft') goTo(step - 1);});Each click shows the next settled state as a still frame. To play the transition instead of jumping, seek to the matching data-transitions entry, call unpauseAnimations(), and pause again once getCurrentTime() passes the next breakpoint.
Behavior notes
Section titled “Behavior notes”Reduced motion. Every animated molecule export contains a media query that hides all SMIL elements when the operating system requests reduced motion. The first frame then shows as a static image:
@media (prefers-reduced-motion: reduce) { #molkit-xxxxx animate, #molkit-xxxxx animateTransform, #molkit-xxxxx animateMotion { display: none }}You do not need to handle this preference yourself. If you build custom controls, consider also turning off autoplay when matchMedia('(prefers-reduced-motion: reduce)') matches.
Dark mode. Theme-aware animated exports have the same three dark-mode states as static exports. By default, dark rules apply under the prefers-color-scheme: dark media query. An mk-dark class on the SVG or any ancestor forces dark mode, and an mk-light class turns off the media query. See CSS theming for details and examples.
Element colors inside labels. In a theme-aware animated export, some spans inside rich labels lose their inline color and get the class mk-<Element>, such as mk-O. This happens when the span’s text is one element symbol (for example, the O of a CH3O label) and its color is that element’s palette color. The span then follows the same element rules as atom labels, including dark mode and any host override of .mk-O. Spans in other colors keep their color.
Restart. There is no restart method. svg.setCurrentTime(0) rewinds, and the timeline keeps playing unless you also pause it.
Poster pattern. To show a still until the reader asks for motion, export a static SVG of the same drawing next to the animated one and swap the two on interaction. The cookbook has the full recipe.
Several animations in one file
Section titled “Several animations in one file”Export > Animated SVG > Several, in one file with tabs writes one file that holds several animations. Each animation is its own nested svg element with the class mk-anim-layer. Only the first is shown; the others have display="none". Each layer keeps the ids, CSS, and timing attributes of a single-animation export, with its ids prefixed (a1-, a2-, and so on), so two layers never share an id.
The root svg element carries data-duration, data-breakpoints, and data-transitions copied from the first layer, so a player that knows nothing about layers plays the first animation correctly. data-mk-animations lists every layer as JSON:
[ { "layer": "a1-molkit-jjgjp", "name": "SN1", "title": "SN1 mechanism", "duration": "4.200", "breakpoints": "0.000,1.500,4.200", "transitions": "0.500,2.000" }, { "layer": "a2-molkit-hnmqt", "name": "SN2", "duration": "3.951", "breakpoints": "0.000,3.951", "transitions": "1.000" }]All layers share the root’s one SMIL clock, because a nested svg element is not a time container. To show another layer, a player does what the built-in tabs do:
const meta = JSON.parse(svg.dataset.mkAnimations);meta.forEach((m, k) => { const layer = svg.getElementById(m.layer); if (k === i) layer.removeAttribute('display'); else layer.setAttribute('display', 'none');});for (const key of ['duration', 'breakpoints', 'transitions']) svg.setAttribute('data-' + key, meta[i][key]);svg.setCurrentTime(0); // the chosen animation starts from its first stateThe file’s own tab bar (g#mk-tabs) is hidden in the file and shown by an inline script, which also widens the viewBox to make room above the drawing. To supply your own tabs, add a data-mk-host-controls attribute to the root. The file’s script then leaves its tab bar hidden.
After each switch, the built-in tabs dispatch an mk-layer-change event on the root, with detail.index and detail.name. In a theme-aware export the tabs, like the layers, follow the reader’s dark-mode preference and a mk-dark or mk-light class on the root or on an element around it.
LaTeX solution exports
Section titled “LaTeX solution exports”A LaTeX solution animation exports differently. The file has no SMIL elements. Every line, term, and strike-through is animated by CSS @keyframes in a style block inside the SVG, and all of them share one duration with no delays. This changes how you script it:
pauseAnimations(),setCurrentTime(), and the other SMIL methods above have no effect. Use the Web Animations API instead:svg.getAnimations({ subtree: true })returns the running CSS animations, which you can pause or seek through theircurrentTime. For a simple play and pause toggle, set CSSanimation-play-stateon the descendants.- The root element has the class
mkitanddata-molkit-format="latex-anim-1.0". It also has the samedata-duration,data-breakpoints(each line complete), anddata-transitions(each transition start) attributes as a molecule export, so the stepping code above works once you replace the seek call. The root hasrole="img"and anaria-label. Its width is in em and it has no height, so it scales with the surrounding text. - Captions:
data-mk-captions(plain text) anddata-mk-captions-htmlhold one caption per pause, anddata-mk-captions-spokenholds the version that a screen reader reads. A step that pauses on several values lists those pauses indata-mk-substeps, as fractions of the time between the transition and the next breakpoint. Captions match the breakpoints plus substeps one to one.data-mk-start-spokenis the summary read before playback. - Color: the ink is
var(--mk-text-color, currentColor), so the file takes the text color of the page around it, or the color your page sets in--mk-text-color. A\colorin the LaTeX source still takes precedence. A finished line stays at--mk-dim-opacity(0.6 by default) until the last pause. - The file styles two root classes for players:
mk-pausedsets every descendant animation toanimation-play-state: paused, andplayingsets it torunning. - Under reduced motion, a file with neither class removes its animations and shows the final frame, the complete solution. When a player has set
mk-pausedorplaying, the animations stay defined so that the player can still step through them. Printing always shows the finished derivation with every line at full ink.
const svg = document.querySelector('svg.mkit');const anims = svg.getAnimations({ subtree: true });anims.forEach(a => a.pause());// jump to the second settled step, in millisecondsconst t = parseFloat(svg.dataset.breakpoints.split(',')[1]) * 1000;anims.forEach(a => { a.currentTime = t; });See also
Section titled “See also”- Animation export reference for the export dialog, looping, and timing options
- Embed SVG exports for runtime insertion and duplicate ids
- CSS theming for the dark-mode class hooks
- Cookbook for swapping a static figure for its animation
- Developer overview for the other parts of an export