Stimulus & content

Custom HTML/JS

`custom:` runs author HTML, CSS, and JavaScript inside the survey. Three scopes — per-question widgets in a Shadow DOM, survey-wide helpers in light DOM installed on flow-reach, and page layout scaffolds with `data-jet-slot` targets. Write data with `Jet.setValue`; everything else — the DOM, the network, external libraries — is open.

What custom: is

Author HTML/CSS/JS embedded directly in the DSL, running same-realm (no iframe) alongside the survey. Three scopes:

ScopeDSL shapeRunsIsolationUse for
Question-levelcustom: as a question propertyOn every render of that questionShadow DOM (CSS/DOM) + wrapped scriptSelf-contained widgets — draggable shelf, image highlighter, calculator
Survey-level- custom: as a flow item (like - script:)Once when reached in the flow — no-op on re-entry, replayed on reload/reconnectLight DOM (page-level) + wrapped scriptShared modals, tooltips, delegated event handlers reused across many questions
Page-levelcustom: on a - page:On every render of that pageLight DOM; questions render into data-jet-slot="…" targetsLayout scaffolds — concept boards, shelf pages, side-by-side comparisons

All three go through one runtime (window.CustomRuntime) — respondent and builder preview share the same code path, so a widget looks identical in both.

The system of record is always the question. Custom code is an input device; its output flows through Jet.setValue into a question, and from there validation, skip logic, quotas, piping, and export all see a normal answer.

Question-level custom: — Shadow DOM

Attached to any question type. Mounts into a Shadow DOM on the question’s host — CSS and IDs are scoped, but --jet-* theme tokens still pierce in, so your widget picks up the survey’s theme for free.

- qid: QDots
    type: number
    text: Tap dots, then confirm the count below.
    custom: |
        <style>
          .dot { display:inline-block; width:24px; height:24px; margin:4px;
                 background:var(--jet-primary); border-radius:50%; cursor:pointer }
          .dot.on { background:var(--jet-accent) }
        </style>
        <div id="grid"></div>
        <script>
          var tapped = 0;
          for (var i = 0; i < 12; i++) {
            var dot = document.createElement('div');
            dot.className = 'dot';
            dot.addEventListener('click', function () {
              if (this.classList.contains('on')) return;
              this.classList.add('on');
              tapped++;
              Jet.setValue('QDots', tapped);   // ← the only write
            });
            root.getElementById('grid').appendChild(dot);
          }
        </script>

The script is lifted into a function wrapper — Jet, root (the question’s shadow root), and state (a per-question object) just exist as function params. tapped stays private (never on window) so other questions can reuse the same variable names.

What root and state are

  • root — the shadow root. Use it (root.getElementById(…), root.querySelector(…)) instead of document so queries stay scoped to this widget.
  • state — a stable per-question object that survives re-visits within a warm page. Cache expensive objects here (a chart instance, a parsed dataset) — the runtime re-runs your script every time the question shows, so re-use rather than re-create. state is NOT durable — it’s dropped on hard reload. The only durable channel is Jet.setValue → question → server.

Survey-level - custom: — light DOM, once

A flow item, parallel to - script: / - note:. Lives in the main page’s light DOM so it can overlay the whole survey and be reused. Runs once — the first time the flow reaches it — then persists for the session.

- custom: |
    <style>
      .cx-backdrop { position:fixed; inset:0; background:rgba(0,0,0,.6);
                     display:none; align-items:center; justify-content:center;
                     z-index:9999 }
      .cx-backdrop.open { display:flex }
      .cx-modal { max-width:min(90vw,720px); padding:16px;
                  background:var(--jet-surface); color:var(--jet-text);
                  border-radius:12px }
      .cx-modal img { max-width:100%; height:auto; display:block }
    </style>
    <script>
      var CONCEPTS = { hero: { img: 'https://cdn.example.com/hero.jpg' } };
      var back = document.createElement('div');
      back.className = 'cx-backdrop';
      back.innerHTML = '<div class="cx-modal"></div>';
      root.appendChild(back);
      var box = back.querySelector('.cx-modal');

      function openConcept(key) {
        var c = CONCEPTS[key]; if (!c) return;
        box.innerHTML = c.img ? '<img src="' + c.img + '">' : c.html;
        back.classList.add('open');
      }
      back.addEventListener('click', function (e) {
        if (e.target === back) back.classList.remove('open');
      });

      // Event delegation reaches any current or future question:
      document.addEventListener('click', function (e) {
        var t = e.target.closest('[data-concept]');
        if (t) { e.preventDefault(); openConcept(t.getAttribute('data-concept')); }
      });

      Jet.modal = openConcept;   // publish as a shared helper
    </script>

- qid: Q2
    type: single
    text: How appealing is this? <a href="#" data-concept="hero">(see the concept)</a>
    options: appealOptions

root in a survey-level block is document.body, and state is a survey-global object.

Activation, replay, and placement

  • Installs on flow-reach, not eagerly at boot. A block behind an untaken branch is correctly not installed.
  • Re-entry is a no-op. Re-reaching the same block (loop iteration, Back-and-forward, branch rejoin) never re-runs it. This is what prevents duplicated event listeners.
  • Replay on cold load / reconnect / deep-link. The activated set is persisted per-respondent; before rendering the current step on resume, the runtime replays every previously-reached block in traversal order — so a respondent who resumes at Q40 still has every helper installed.
  • Legal anywhere. - custom: is valid at root and inside if / elif / else / loop / page / block. A block inside a loop installs on the first iteration reached and is a no-op thereafter — for per-iteration behaviour use question-level custom: instead.

Page-level custom: — layout scaffold with slots

A custom: block on a - page: is a layout scaffold. The page’s member questions render into elements you mark with data-jet-slot="<qid>" (or data-jet-slot="default" as a catch-all).

- page: shelfConcept
    text: Rate this concept.
    custom: |
        <div class="concept-page">
          <div class="hero" data-jet-slot="QReaction"></div>
          <div class="row">
            <div class="cell" data-jet-slot="QAppeal"></div>
            <div class="cell" data-jet-slot="QRelevance"></div>
            <div class="cell" data-jet-slot="QUnique"></div>
          </div>
        </div>
        <style>
          .concept-page { display:grid; gap:24px }
          .row { display:grid; grid-template-columns:repeat(3,1fr); gap:16px }
        </style>
    questions:
        - qid: QReaction
            type: rating
            text: First reaction?
        - qid: QAppeal
            type: single
            text: Appealing?
            options: yesNo
        - qid: QRelevance
            type: single
            text: Relevant?
            options: yesNo
        - qid: QUnique
            type: single
            text: Unique?
            options: yesNo

The runtime lays out the member cards normally, then relocates each into its slot. Renders identically in the live respondent and the builder preview — one shared render path (CustomRuntime.mountPageScaffold).

Unlike survey-level - custom:, page-level scaffolds do not persist across pages and don’t need data-jet-* reserved plumbing beyond the slot attribute.

The Jet bridge

The only supported way to read or write survey state from custom code.

MethodPurpose
Jet.getValue(qid)Read a question’s current answer.
Jet.setValue(qid, value)Write a value into a question. Value shape must match the target type (single → code, rank → ordered code list, gridSingle → {row: code}, number → number).
Jet.onCleanup(fn)Register a teardown callback. See Cleanup below.

Writes ride the next forward /step as body.customAnswers; the server merges them into state.answers before executing, so they persist and export like any other answer. A write to the current step’s own qid is captured through the normal answer payload. {{ }} piping works inside custom: blocks — resolved before the block mounts.

Loop-aware Jet

Inside a loop, Jet binds to the current iteration. A bare qid that names a loop member hits that iteration’s slot (Q1|<loopId>=<code>), not the bare Q1. Outer-loop members from a nested loop resolve to their current outer iteration.

Cross-iteration access (read/write a different iteration than the current one) is not in v1 — bare = current iteration.

Cleanup

The question-level script re-runs every time the question shows. Listeners/timers you attached outside root (on document or window, setTimeout/setInterval, Observer instances, in-flight fetch) will pile up unless you tear them down. Register with Jet.onCleanup(fn):

var timer = setInterval(poll, 1000);
var onKey = function (e) { /* … */ };
document.addEventListener('keydown', onKey);   // OUTSIDE root → must clean up

Jet.onCleanup(function () {
  clearInterval(timer);
  document.removeEventListener('keydown', onKey);
});
// Listeners on root.querySelector(…) need no cleanup — they die with root.

Callbacks fire in LIFO order at two moments: immediately before the block’s script re-runs, and when the respondent navigates away from the step. After firing, the list empties; the next run re-registers fresh. state is not cleared by cleanup.

Writing data — two patterns

Both use the same wire (Jet.setValue). Choice depends on shape.

Capture into a hidden open-end

Fits any shape as JSON. Trade-off: opaque to DSL logic and the data map.

- qid: shelfData
    type: open
    visibility: hide   # the sink — respondent never sees it

- qid: shelfUI
    type: info
    title: Drag the products onto the shelf, best-seller first.
    custom: |
        <div class="shelf" id="shelf">
          <div class="tile" draggable="true" data-sku="A">Cola</div>
          <div class="tile" draggable="true" data-sku="B">Lemonade</div>
        </div>
        <script>
          var shelf = root.getElementById('shelf');
          function persist() {
            var order = [].map.call(shelf.children, function (t) { return t.dataset.sku; });
            Jet.setValue('shelfData', JSON.stringify(order));
          }
          var prior = Jet.getValue('shelfData');
          if (prior) applyOrder(JSON.parse(prior));
          shelf.addEventListener('drop', persist);
        </script>

shelfData exports as one text column holding ["B","A"].

Write straight into typed questions

DSL logic, quotas, piping, and export all see the answer natively. Cost: value must match the type’s shape.

- qid: shelfRank
    type: rank
    visibility: hide
    options:
        A: Cola
        B: Lemonade
        C: Water

- qid: shelfUI
    type: info
    custom: |
        <script>
          function persist() {
            var order = [].map.call(shelf.children, function (t) { return t.dataset.sku; });
            Jet.setValue('shelfRank', order);   // rank wants ordered codes → ['B','A','C']
          }
        </script>

One block can drive several hidden typed questions (a bespoke form).

visibility: hide is not a native-write target. Hidden questions have no DOM element to querySelector, so Jet.setValue is the only mechanism that reaches them. Trying to bypass Jet and hit hidden inputs via DOM will silently do nothing on the live path.

External assets — scripts and stylesheets

External <link rel="stylesheet"> and <script src> are loaded normally.

  • Deduped by URL — five questions sharing the same lib fetch it once.
  • Executed in authored order — external + inline scripts run as one sequential chain, top to bottom, exactly as written. An inline script after a <script src> waits for the external to load.
  • Inside a shadow root, an external stylesheet is auto-scoped to the question.
  • Inline scripts run through the function wrapper (Jet/root/state in scope). External scripts run at page level and expose their normal globals (window.Chart, window.$, etc.) — which is how libraries expect to work.
custom: |
    <link rel="stylesheet" href="https://cdn.example.com/shelf.css">
    <script src="https://cdn.example.com/shelf-lib.js"></script>       <!-- 1: loads window.ShelfLib -->
    <script src="https://cdn.example.com/shelf-plugin.js"></script>    <!-- 2: waits for #1 -->
    <div id="shelf"></div>
    <script>
      // 3: runs after 1 AND 2 → ShelfLib + plugin ready
      var s = new ShelfLib(root.getElementById('shelf'));
      s.onChange(function (order) { Jet.setValue('shelfData', JSON.stringify(order)); });
    </script>

Session guard

Custom code runs same-realm, so the runtime does one thing to protect its own plumbing: the native fetch and XMLHttpRequest are captured before any author code runs, and the client-carried session token stays a private closure variable — never on window, localStorage, or a cookie. A hostile window.fetch = … override in custom code can’t intercept the token.

This is best-effort hardening for trusted authors, not a sandbox. The DOM, network, and external APIs are open by design — a trusted programmer team can fetch any URL, call their own analytics, load a proprietary SDK. Untrusted authoring would need a separate enforcement layer the platform can add later if the audience ever includes self-serve.

Reserved namespaces

Keep these free for platform instrumentation:

  • The jet- class prefix (<div class="jet-foo">)
  • data-jet-* HTML attributes (including data-jet-slot)
  • The Jet.* global (add helpers with Jet.myHelper = … from a survey-level block, but don’t reassign Jet itself)

Author-facing helpers you publish from a survey-level - custom: block — Jet.modal, Jet.trackClick, etc. — are exactly the intended way to extend Jet.

When custom: is the wrong tool

  • Emphasis or simple HTML — use Safe HTML in text:.
  • Image / audio / video stimulus alone — use Media.
  • Skin variants — use the question’s style: property.
  • Reading URL params — use request.param(...) in a - script: and pass through a hidden question.

Caveats

Custom content bypasses every sanitiser. Whatever you write in custom: runs verbatim. Review it like production code — no CSP, no allow-list. Trusted authors only.
Native DOM writes are unsupported. A programmer can technically document.querySelector a rendered input and set its value + dispatch change. It might work today; it can break silently on any release. Jet.setValue is the only supported write path.
state vs. Jet. Use state to cache things between re-runs within a warm page (a library instance, a parsed dataset). Use Jet.setValue for anything the survey needs to see — validation, logic, export, replay after reconnect.

See also

  • Safe HTML — non-interactive markup that doesn’t need the escape hatch
  • Inline CSS — styling that the allow-list covers
  • Pages — page-scoped custom: scaffolds and slots
  • Scripts — pair - script: with custom: to capture URL params or compute derived values