Skip to content

Cookbook

These recipes solve common integration tasks with plain JavaScript and CSS, without a framework or a build step. Each recipe lists the export it needs.

Highlight every atom of an element on hover

Section titled “Highlight every atom of an element on hover”

Goal: when the reader points at any oxygen, pick out all the oxygens in the structure.

Requires: a static SVG export. The recipe reads data-mk-element, which every export includes.

element-hover.html
<style>
/* CSS-only variant: hovering one O dims everything that is not an O */
.mol:has(.atom-group[data-mk-element="O"]:hover)
.atom-group:not([data-mk-element="O"]),
.mol:has(.atom-group[data-mk-element="O"]:hover)
.bond-group {
opacity: 0.25;
transition: opacity 0.15s;
}
/* Used by the JS variant below */
.atom-group.is-highlighted {
filter: drop-shadow(0 0 3px #fab005);
}
</style>
<div class="mol"><!-- inline SVG export here --></div>
<script>
// JS variant: works in any browser and for any element, not only O
document.querySelectorAll('.mol .atom-group[data-mk-element]').forEach(atom => {
const symbol = atom.dataset.mkElement;
const peers = () =>
document.querySelectorAll(`.mol .atom-group[data-mk-element="${symbol}"]`);
atom.addEventListener('pointerenter', () =>
peers().forEach(a => a.classList.add('is-highlighted')));
atom.addEventListener('pointerleave', () =>
peers().forEach(a => a.classList.remove('is-highlighted')));
});
</script>

How it works: every atom is a g.atom-group with data-mk-element, so one attribute selector matches all atoms of an element. Theme-aware exports set element colors with !important, which a plain fill override cannot beat. The CSS variant therefore dims the other atoms instead of recoloring the matches; opacity and filter are not affected by the !important color rules. The CSS variant needs :has() support, so the JS variant also serves as the fallback.

Goal: show hybridization, geometry, and formal charge in a tooltip that follows the pointer.

Requires: a static SVG export.

atom-tooltip.html
<style>
.atom-tip {
position: fixed; z-index: 10; pointer-events: none;
background: #222; color: #fff; padding: 4px 8px;
border-radius: 4px; font: 13px/1.4 system-ui; white-space: pre-line;
}
</style>
<script>
const tip = document.createElement('div');
tip.className = 'atom-tip';
tip.hidden = true;
document.body.appendChild(tip);
const svg = document.querySelector('.mol svg');
svg.addEventListener('pointerover', e => {
const atom = e.target.closest('[data-mk-element]');
if (!atom) return;
const d = atom.dataset;
const lines = [d.mkElement];
if (d.mkHybridization) lines.push('Hybridization: ' + d.mkHybridization);
if (d.mkGeometry) lines.push('Geometry: ' + d.mkGeometry);
if (d.mkFormalCharge && d.mkFormalCharge !== '0')
lines.push('Formal charge: ' + d.mkFormalCharge);
tip.textContent = lines.join('\n');
tip.hidden = false;
});
svg.addEventListener('pointermove', e => {
tip.style.left = e.clientX + 14 + 'px';
tip.style.top = e.clientY + 14 + 'px';
});
svg.addEventListener('pointerout', e => {
if (e.target.closest('[data-mk-element]')) tip.hidden = true;
});
</script>

How it works: one delegated pointerover listener on the SVG finds the atom under the pointer with closest(), so it keeps working if you swap the molecule. Molkit omits hybridization and geometry when it cannot determine them, so the code checks each attribute before adding its line.

Goal: a small teaching panel that shows an atom’s or bond’s chemistry when the reader clicks it. The per-atom and per-bond data-mk-* attributes supply all the data, with no server or chemistry library.

Requires: a static SVG export.

structure-inspector.html
<div class="mol-row" style="display: flex; gap: 1rem;">
<div id="mol"><!-- inline SVG export with metadata here --></div>
<aside id="inspector" style="min-width: 14rem;">Click an atom or bond.</aside>
</div>
<script>
const panel = document.getElementById('inspector');
function row(label, value) {
return value == null ? '' : `<dt>${label}</dt><dd>${value}</dd>`;
}
function renderAtom(d) {
panel.innerHTML = `<h3>${d.mkElement} atom</h3><dl>` +
row('Formal charge', d.mkFormalCharge) +
row('Lone pairs', d.mkLonePairs) +
row('Hybridization', d.mkHybridization) +
row('Geometry', d.mkGeometry) +
row('Octet', d.mkOctet) +
'</dl>';
}
function renderBond(d) {
const names = { 1: 'single', 2: 'double', 3: 'triple' };
const polarity = d.mkPolarity
? `${d.mkPolarity} (toward ${d.mkPolarToward})` : null;
panel.innerHTML = '<h3>Bond</h3><dl>' +
row('Order', names[d.mkOrder] ?? d.mkOrder) +
row('Stereo', d.mkStereo) +
row('Polarity', polarity) +
'</dl>';
}
document.querySelectorAll('#mol .atom-group[data-mk-element]').forEach(a =>
a.addEventListener('click', () => renderAtom(a.dataset)));
document.querySelectorAll('#mol .bond-group[data-mk-order]').forEach(b =>
b.addEventListener('click', () => renderBond(b.dataset)));
</script>

How it works: the code finds atoms by data-mk-element and bonds by data-mk-order, the two attributes that every atom group and bond group has. All other attributes are conditional, so row() skips missing values instead of printing “undefined”.

  • The octet value is satisfied, deficient, or expanded. It is absent where the octet is undefined: generic atoms, bridging hydrogens, and bare metal ions.
  • Polarity appears only on bonds with an electronegativity difference of at least 0.05.
  • Generic placeholder atoms carry only data-mk-element="*", data-mk-generic, and their label, so the panel shows only the heading for them.

You can extend the panel into a quiz (“predict the hybridization, then click to check”) or a step-by-step Lewis structure exercise.

Goal: show the static structure by default and play its animated version on request.

Requires: both exports inlined on the page, for example reaction.svg and reaction-animation.svg.

anim-toggle.html
<div id="reaction">
<span class="static"><!-- inline reaction.svg --></span>
<span class="animated" hidden><!-- inline reaction-animation.svg --></span>
</div>
<button id="play">Play animation</button>
<script>
const staticView = document.querySelector('#reaction .static');
const animView = document.querySelector('#reaction .animated');
const btn = document.getElementById('play');
let playing = false;
btn.addEventListener('click', () => {
playing = !playing;
staticView.hidden = playing;
animView.hidden = !playing;
btn.textContent = playing ? 'Show static' : 'Play animation';
if (playing) {
const svg = animView.querySelector('svg');
svg.setCurrentTime(0); // restart from the first state
svg.unpauseAnimations();
}
});
</script>

How it works: an animated export runs on one SMIL timeline, so setCurrentTime(0) followed by unpauseAnimations() restarts it. Without the rewind, showing the animation again would resume it partway through. The static figure stays in the DOM, so switching back is instant. For all playback methods, see Control animated SVGs.

Goal: your site has its own light and dark toggle, and embedded SVGs should follow it instead of the operating system setting.

Requires: theme-aware exports from Molkit 0.19.0 or later. Earlier theme-aware exports may respond only to the operating system setting.

theme-sync.js
const wrapper = document.querySelector('main');
function syncMolkitTheme(dark) {
wrapper.classList.toggle('mk-dark', dark);
wrapper.classList.toggle('mk-light', !dark);
}
// Call from your existing toggle; for example:
syncMolkitTheme(document.documentElement.dataset.theme === 'dark');

How it works: every theme-aware export has two hooks for its dark rules: the prefers-color-scheme media query, and an mk-dark class on the SVG or any ancestor that forces dark mode. The mk-light class does the opposite: it turns off the media query, so a site set to light never shows dark embeds. Setting the classes on one shared wrapper themes every embed on the page. CSS theming explains the generated CSS.

Goal: run cheminformatics (canonical SMILES, descriptors, substructure search) on the embedded structure in the browser.

Requires: a static SVG export of a single species; the MOL block is written only for one species. RDKit.js from a CDN downloads roughly 9 MB of WebAssembly, so load it only when needed.

rdkit-smiles.html
<script src="https://unpkg.com/@rdkit/rdkit@2026.9.1/dist/RDKit_minimal.js"></script>
<script>
function molBlockFrom(svg) {
const meta = svg.querySelector('metadata');
if (!meta) return null;
for (const block of meta.children) {
if (block.localName !== 'chemistry') continue;
for (const child of block.children) {
if (child.localName === 'mol-block') return child.textContent;
}
}
return null;
}
initRDKitModule().then(RDKit => {
const molBlock = molBlockFrom(document.querySelector('.mol svg'));
if (!molBlock) return;
const mol = RDKit.get_mol(molBlock);
console.log(mol.get_smiles()); // canonical SMILES
console.log(mol.get_descriptors()); // computed properties (JSON)
mol.delete(); // RDKit objects must be freed manually
});
</script>

How it works: an export of a single species embeds a standard V2000 MOL block in a namespaced mk:chemistry block inside the SVG’s metadata element. The lookup matches on localName instead of the tag name, because namespaced selectors behave differently across browsers. Any tool that reads V2000 accepts the MOL block text; RDKit.js runs in the browser.

Step through an animation with the arrow keys

Section titled “Step through an animation with the arrow keys”

Goal: present an animated mechanism one state at a time with the arrow keys instead of letting it play through.

Requires: an animated export, inlined.

step-through.html
<div class="anim"><!-- inline reaction-animation.svg --></div>
<p id="anim-status" aria-live="polite"></p>
<script>
const svg = document.querySelector('.anim svg');
const status = document.getElementById('anim-status');
const breakpoints = svg.dataset.breakpoints.split(',').map(Number);
let state = 0;
function seek(i) {
state = Math.max(0, Math.min(i, breakpoints.length - 1));
svg.setCurrentTime(breakpoints[state]);
status.textContent = `State ${state + 1} of ${breakpoints.length}`;
}
svg.pauseAnimations();
seek(0);
document.addEventListener('keydown', e => {
if (e.key === 'ArrowRight') seek(state + 1);
if (e.key === 'ArrowLeft') seek(state - 1);
});
</script>

How it works: the root of an animated export has data-breakpoints, a comma-separated list of the times (in seconds) at which each state has fully settled. The first entry is 0, for the initial state. With the timeline paused, setCurrentTime at a breakpoint shows that state as a still frame, so each arrow key moves one state. For richer players, use data-duration and data-transitions too; see Control animated SVGs.

Show a figure’s potential map in place of the drawing

Section titled “Show a figure’s potential map in place of the drawing”

Goal: open a page on a molecule’s electrostatic potential map instead of its 2D drawing, at the angle the author chose.

Requires: an SVG exported with a map (see Electrostatic potential maps), and the Molkit Viewer, with molkit-widget-esp.js in the same folder as molkit-widget.js. This recipe uses the viewer instead of an inline SVG.

map-figure.js
// Separate .esp files that are not beside their SVGs live here (looked up by file name).
MolkitWidget.espBase = '/files/esp/';
MolkitWidget.mount(document.getElementById('water-map'), {
src: '/img/water.svg',
espAuto: true,
});

How it works: espAuto opens the viewer on its 3D tab and turns the map on as soon as the 3D view is ready. If the author exported with the map showing in Molkit’s 3D viewer, the SVG stores that camera angle in mk:esp-display, and the viewer starts there once; after that, the reader can turn the model freely. The map code and data download only for a figure opened this way, or when a reader clicks the map button.