Skip to main content
Recipe number 215

Cookbook · Chapter 13 · CMS integration

Notes in the margin, with a popover from page coordinates

Note marks tint their words and flag them in the outer margin; a press opens the note in a popover placed under the words with rangeRects and pageToClient.

On this page
Output
Canvas
Postext
Tested with Postext 1.103.1
Needs ≥ 1.103.0
Licence
Updated 4 Dec 2026
Code MIT · Text CC BY 4.0
Four reviewer's notes on a museum text: each tints its words and runs a dashed line to a numbered flag in the wide margin; note 2 is open under its words.
Four reviewer's notes on a museum text: each tints its words and runs a dashed line to a numbered flag in the wide margin; note 2 is open under its words.
  • Trim 160 × 220 mm
  • 1 column
  • Alegreya 10.5/15
  • Alegreya Sans
  • 1 page
  • Level
  • Postext 1.103.1
  • Laid out in 45 ms
  • 118 lines of code

In short

A museum's gallery text with a reviewer's notes on it. Each note shades its words and puts a numbered tag in the wide right margin, joined by a dashed line. Pressing a tag opens the note in a small box right under its words.

What you'll build

A museum's gallery text on the Antikythera mechanism, as an exhibition editor sees it with the reviewer's notes. Each of the four notes tints its words and runs a dashed leader to a numbered flag in the wide outer margin. Note 2 is open: a popover with the reviewer's comment sits just under the words it is about, its pointer on the last of them. Press another flag, or the tinted words, and the popover moves there; scroll or resize and it stays with its words.

This recipe answers

  • How do I place a note or a popover beside a passage of the laid-out page?

The short answer

script.js · lines 108–130in full code
const view = createViewer(document.getElementById('viewer'), {
  document: doc, markdown, zoom: 'fit-width', maxZoom: 1, labels: L.viewer,
  marks: { noteSide: 'end' }, // the flags in the outer margin, not the nearer one
  annotations: notes.map(({ id, label, range }) => ({ id, kind: 'note', range, label })),
});
let open = null; // the note the popover shows
const place = () => {
  if (!open) return;
  // Under the last piece of the noted words: page px, turned into the window's px.
  const last = rangeRects(doc, open.range).at(-1);
  const at = last && view.pageToClient(last.pageIndex, last.rect.x, last.rect.y + last.rect.height);
  pop.hidden = !at;
  if (at) Object.assign(pop.style, { left: `${at.x}px`, top: `${at.y + 8}px` });
};
const show = (id) => {
  open = notes.find((n) => n.id === id) ?? null;
  if (open) fill(open);
  place();
};
view.on('annotationclick', ({ id }) => show(id)); // a flag or the tinted words
view.on('zoomchange', place); // the pages moved under the popover
view.element.addEventListener('scroll', place, { capture: true, passive: true });
show('n2');

Note flags in the margin, and a popover placed from page coordinates

Ingredients

Type
Alegreya, Alegreya Sans (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · Leave a margin for the flags

script.js · lines 29–49in full code
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(160), height: mm(220), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(18), right: mm(42) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Alegreya', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'left', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Alegreya Sans', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(4), marginBottom: pt(15) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Alegreya Sans',
      fontSize: pt(8.5), fontWeight: 700, color: col('accent'), align: 'left',
      placement: { anchor: { to: 'page', edge: 'bottom-left' },
        offset: { x: mm(18), y: mm(-12) } } },
  ] },
};

A 42 mm outer margin takes the flags without crowding the text. The viewer's marks option passes noteSide: 'end' to the marks layout, so every flag goes to the right-hand margin; by default each takes the nearer margin of its line. Flags on the same height stack down the margin without overlapping, and a label too long for it is cut short with an ellipsis.

#2 · Keep the notes as ranges with labels

script.js · lines 80–96in full code
// A tool stores the offsets; the pen finds them from quotes so that both editions run.
const notes = t({
  en: [['In the spring of 1901', 'The wreck was found in 1900; the mechanism came up in 1901.'],
    ['a small ball, half silver and half dark',
      'Is the ball still there? If not, say it is reconstructed.'],
    ['nineteen-year calendar', 'Name it: the Metonic cycle. Readers will look it up.'],
    ['X-ray scans', 'Give the year of the scans, 2005.']],
  es: [['En la primavera de 1901', 'El naufragio se halló en 1900; el mecanismo salió en 1901.'],
    ['una bolita, mitad plateada y mitad oscura',
      '¿Se conserva la bolita? Si no, di que es una reconstrucción.'],
    ['calendario de diecinueve años', 'Dale su nombre: el ciclo metónico. El lector lo buscará.'],
    ['radiografías', 'Pon el año de las radiografías, 2005.']],
}).map(([quote, body], i) => {
  const start = markdown.indexOf(quote);
  const range = { start, end: start + quote.length };
  return { id: `n${i + 1}`, label: String(i + 1), body, range };
});

A note mark needs a range and a short label for its flag, a number or an initial. The comment itself, its author and its thread stay in the host's records; the mark only says where they belong.

#3 · Place the popover from page coordinates

The code is the short answer above. rangeRects gives the noted words' pieces in page px; the last piece's bottom-left corner, passed to pageToClient, comes back in window px, ready for a position: fixed element. The viewer reports its opening zoom on its first frame, so listening to zoomchange places the opening popover again once the pages are painted, and a scroll listener on view.element keeps it under its words.

The whole recipe

// ═══ Postext Cookbook · Nº 215 · Notes in the margin, with a popover ═════════════════
// https://postext.dev/en/cookbook/margin-notes-with-popovers
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Alegreya, Alegreya Sans (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A museum's gallery text with a reviewer's notes on it: each note tints its words and
// puts a numbered flag in the outer margin. Pressing a flag opens the note in a popover,
// which the host places under the words from their page coordinates. Note 2 opens itself.
import { buildDocumentWithFonts, renderPageToCanvas, rangeRects } from 'https://esm.sh/postext';
import { createViewer } from 'https://esm.sh/postext-viewer';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'margin-notes-with-popovers';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#211f1c', // text
  accent: '#9a4b16', // bronze: title and folio
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion

// #region page: a wide outer margin, where the reviewer's flags go
const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(160), height: mm(220), dpi: 150,
    margins: { top: mm(20), bottom: mm(24), left: mm(18), right: mm(42) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Alegreya', fontSize: pt(10.5), lineHeight: pt(15),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'left', firstLineIndent: mm(5), indentAfterHeading: false,
    hyphenation: { enabled: true }, avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Alegreya Sans', color: col('accent'), fontWeight: 700, levels: [
    { level: 1, fontSize: pt(22), lineHeight: pt(26), marginTop: pt(4), marginBottom: pt(15) },
  ] },
  header: { elements: [] },
  footer: { elements: [
    { kind: 'text', id: 'folio', content: '{pageNumber}', fontFamily: 'Alegreya Sans',
      fontSize: pt(8.5), fontWeight: 700, color: col('accent'), align: 'left',
      placement: { anchor: { to: 'page', edge: 'bottom-left' },
        offset: { x: mm(18), y: mm(-12) } } },
  ] },

The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)

Variations

#Open a note on hover

The hover event carries the ids of the marks under the pointer, the top one first.

 view.on('annotationclick', ({ id }) => show(id)); // a flag or the tinted words
+view.on('hover', ({ annotations }) => annotations[0] && show(annotations[0]));

#Let each flag take the nearer margin

In a two-column page the left column's notes then flag into the left margin.

-  marks: { noteSide: 'end' }, // the flags in the outer margin, not the nearer one
+  marks: {}, // each flag in the margin nearer its words

Credits

Text
Original prose, CC BY 4.0
Fonts
Alegreya (SIL OFL 1.1) · Alegreya Sans (SIL OFL 1.1)