// Mass on a frictionless spring. Positions are in units of the maximum // swing drawn on screen, so q lies in [-1, 1]. function color(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); } // Size a canvas for the device pixel ratio and return its context and CSS size. function prepare(canvas) { const ctx = canvas.getContext('2d'); const dpr = window.devicePixelRatio || 1; const w = canvas.clientWidth; const h = canvas.clientHeight; if (canvas.width !== w * dpr || canvas.height !== h * dpr) { canvas.width = w * dpr; canvas.height = h * dpr; } ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, w, h); return { ctx, w, h }; } // Horizontal layout shared by the spring diagram, the q0 slider and the phase plot, // so that a given q sits at the same x on all of them. function layout(w) { const rest = w * 0.5; const swing = Math.min(w * 0.3, 200); return { rest, swing, qToX: (q) => rest + q * swing }; } // params: { k, m, q0 }, read live so sliders can change them. // labels: which of 'm', 'k', 'q', 'F', 'p', 'q0' to draw. // pScale: length of the p arrow per unit momentum, as a fraction of the swing; // by default the arrow peaks at the same length as q. function createSpring({ canvas, button, params, labels = [], speed = 1, pScale, onDraw = () => {} }) { let q = params.q0; let p = 0; function step(dt) { // velocity Verlet on dq/dt = p/m, dp/dt = -k q const { k, m } = params; const f = -k * q; q += (p / m) * dt + (0.5 * f / m) * dt * dt; p += 0.5 * (f - k * q) * dt; } function draw() { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const fg = color('--fg'); const accent = color('--accent'); const { rest, swing, qToX } = layout(w); const wallX = 20; const floorY = h * 0.62; const box = 50; const center = qToX(q); const boxX = center - box / 2; const springY = floorY - box / 2; // wall and floor ctx.strokeStyle = fg; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(wallX, floorY - box * 1.6); ctx.lineTo(wallX, floorY); ctx.lineTo(w - 10, floorY); ctx.stroke(); // spring (zig-zag) const coils = 12; const amp = 10; const start = wallX; const end = boxX; const lead = 12; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(start, springY); ctx.lineTo(start + lead, springY); const len = end - start - 2 * lead; for (let i = 0; i < coils; i++) { const sx = start + lead + ((i + 0.5) / coils) * len; ctx.lineTo(sx, springY + (i % 2 ? amp : -amp)); } ctx.lineTo(end - lead, springY); ctx.lineTo(end, springY); ctx.stroke(); // mass ctx.fillStyle = accent; ctx.fillRect(boxX, floorY - box, box, box); // rest position marker ctx.strokeStyle = fg; ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(rest, floorY - box * 1.4); ctx.lineTo(rest, floorY + 34); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; onDraw(q, p); if (!labels.length) return; ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'center'; if (labels.includes('m')) { ctx.fillStyle = color('--bg'); ctx.textBaseline = 'middle'; ctx.fillText('m', center, floorY - box / 2); } if (labels.includes('k')) { ctx.fillStyle = fg; ctx.textBaseline = 'bottom'; ctx.fillText('k', (start + end) / 2, springY - amp - 4); } if (labels.includes('q0')) { // where the block was let go from const x0 = qToX(params.q0); ctx.strokeStyle = fg; ctx.globalAlpha = 0.5; ctx.setLineDash([2, 3]); ctx.beginPath(); ctx.moveTo(x0, floorY - box - 34); ctx.lineTo(x0, floorY); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; ctx.fillStyle = fg; ctx.textBaseline = 'bottom'; ctx.fillText('q₀', x0, floorY - box - 36); } // q below the floor; F and p above the block const { k, m } = params; const pLen = (pScale ?? 1 / Math.sqrt(k * m)) * swing; if (labels.includes('q')) arrow(ctx, rest, center, floorY + 22, fg, 'q', 'below'); if (labels.includes('F')) arrow(ctx, center, center - q * swing, floorY - box - 40, color('--force'), 'F', 'above'); if (labels.includes('p')) arrow(ctx, center, center + p * pLen, floorY - box - 14, color('--momentum'), 'p', 'above'); } function setLabels(value) { labels = value; draw(); } const loop = createLoop({ button, step, draw, speed }); // Back to being held at q0, at rest. function reset() { q = params.q0; p = 0; loop.reset(); } return { draw, setLabels, reset, pause: loop.pause }; } // Animation driven by a Start / Stop / Continue button. function createLoop({ button, step, draw, speed = 1 }) { let running = false; let lastTime = null; let rafId = null; function frame(t) { if (!running) return; if (lastTime !== null) { const dt = speed * Math.min((t - lastTime) / 1000, 0.05); const n = 4; for (let i = 0; i < n; i++) step(dt / n); } lastTime = t; draw(); rafId = requestAnimationFrame(frame); } function setRunning(value) { running = value; cancelAnimationFrame(rafId); if (running) { lastTime = null; rafId = requestAnimationFrame(frame); } if (running || button.textContent !== 'Start') { button.textContent = running ? 'Stop' : 'Continue'; } } button.addEventListener('click', () => setRunning(!running)); window.addEventListener('resize', draw); return { pause: () => running && setRunning(false), reset: () => { setRunning(false); button.textContent = 'Start'; draw(); }, }; } // Pendulum: a bob of mass m on a massless rod of length L, angle theta from // straight down, kept in [-pi, pi]. // params: { m, L, g, theta0, p0 }, read live so sliders can change them. // labels: which of 'm', 'L', 'theta', 'p', 'g' to draw. // centered: put the pivot mid-canvas so the bob can go over the top; the rod // is then drawn to scale, with L = 1.5 filling the canvas. // pScale: length of the p arrow in px per unit momentum; by default the arrow // peaks at 70px when let go from theta0 at rest. function createPendulum({ canvas, button, params, labels = [], centered = false, pScale, onDraw = () => {} }) { let theta = params.theta0; let p = params.p0; function step(dt) { // leapfrog on dtheta/dt = p / (m L^2), dp/dt = -m g L sin(theta) const { m, L, g } = params; p -= 0.5 * dt * m * g * L * Math.sin(theta); theta += dt * p / (m * L * L); p -= 0.5 * dt * m * g * L * Math.sin(theta); if (theta > Math.PI) theta -= 2 * Math.PI; if (theta < -Math.PI) theta += 2 * Math.PI; } function draw() { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const fg = color('--fg'); const accent = color('--accent'); const { m, L, g } = params; const px = w / 2; const py = centered ? h / 2 : 30; const maxRod = centered ? h / 2 - 28 : Math.min(h - 80, w * 0.4); const rod = centered ? maxRod * L / 1.5 : maxRod; const bx = px + rod * Math.sin(theta); const by = py + rod * Math.cos(theta); const r = 18; // ceiling (only when hanging from the top) and pivot ctx.strokeStyle = fg; ctx.lineWidth = 2; if (!centered) { ctx.beginPath(); ctx.moveTo(px - 50, py); ctx.lineTo(px + 50, py); ctx.stroke(); } // vertical reference ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px, py + rod + r + 10); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; // rod and bob ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(bx, by); ctx.stroke(); ctx.fillStyle = fg; ctx.beginPath(); ctx.arc(px, py, 4, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(bx, by, r, 0, 2 * Math.PI); ctx.fill(); onDraw(theta, p); ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; if (labels.includes('m')) { ctx.fillStyle = color('--bg'); ctx.fillText('m', bx, by); } if (labels.includes('L')) { // beside the middle of the rod, on the side away from the vertical const side = theta >= 0 ? 1 : -1; ctx.fillStyle = fg; ctx.fillText('L', (px + bx) / 2 + side * 14 * Math.cos(theta), (py + by) / 2 - side * 14 * Math.sin(theta)); } if (labels.includes('theta')) { // arc from the vertical to the rod const arcR = Math.min(44, rod * 0.6); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(px, py, arcR, Math.PI / 2, Math.PI / 2 - theta, theta > 0); ctx.stroke(); const mid = Math.PI / 2 - theta / 2; ctx.fillText('θ', px + (arcR + 14) * Math.cos(mid), py + (arcR + 14) * Math.sin(mid)); } if (labels.includes('p')) { // along the direction of motion, perpendicular to the rod const peak = Math.sqrt(2 * m * m * g * L * L * L * (1 - Math.cos(params.theta0))); const len = p * (pScale ?? (peak ? 70 / peak : 0)); const tx = Math.cos(theta); const ty = -Math.sin(theta); const momentum = color('--momentum'); ctx.strokeStyle = momentum; ctx.fillStyle = momentum; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(bx, by); ctx.lineTo(bx + tx * len, by + ty * len); ctx.stroke(); if (Math.abs(len) > 8) { const d = Math.sign(len); const ex = bx + tx * len; const ey = by + ty * len; ctx.beginPath(); ctx.moveTo(ex, ey); ctx.lineTo(ex - d * 8 * tx - 4 * ty, ey - d * 8 * ty + 4 * tx); ctx.lineTo(ex - d * 8 * tx + 4 * ty, ey - d * 8 * ty - 4 * tx); ctx.closePath(); ctx.fill(); ctx.fillText('p', ex + d * 12 * tx, ey + d * 12 * ty); } } if (labels.includes('g')) { // gravity, pointing down, off to the side const gx = Math.min(px + maxRod + 50, w - 20); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(gx, py + 40); ctx.lineTo(gx, py + 90); ctx.stroke(); ctx.beginPath(); ctx.moveTo(gx, py + 90); ctx.lineTo(gx - 4, py + 82); ctx.lineTo(gx + 4, py + 82); ctx.closePath(); ctx.fill(); ctx.fillText('g', gx + 14, py + 65); } } const loop = createLoop({ button, step, draw }); function setLabels(value) { labels = value; draw(); } // Back to the initial state, held still. function reset() { theta = params.theta0; p = params.p0; loop.reset(); } return { draw, setLabels, reset, pause: loop.pause }; } function arrow(ctx, from, to, y, col, label, side) { const dir = Math.sign(to - from); ctx.strokeStyle = col; ctx.fillStyle = col; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(from, y); ctx.lineTo(to, y); ctx.stroke(); if (Math.abs(to - from) > 8) { ctx.beginPath(); ctx.moveTo(to, y); ctx.lineTo(to - dir * 8, y - 4); ctx.lineTo(to - dir * 8, y + 4); ctx.closePath(); ctx.fill(); } ctx.textBaseline = side === 'above' ? 'bottom' : 'top'; ctx.fillText(label, (from + to) / 2, side === 'above' ? y - 4 : y + 4); } // Horizontal bars for kinetic, potential and total energy, scaled to the total. function drawEnergyBars(canvas, params, q, p) { if (!canvas.clientWidth) return; const { ctx, w } = prepare(canvas); const { k, m, q0 } = params; const kinetic = (p * p) / (2 * m); const potential = 0.5 * k * q * q; const total = 0.5 * k * q0 * q0; const fg = color('--fg'); const kColor = color('--momentum'); const pColor = color('--potential'); const labelW = 90; const barW = Math.min(w - labelW - 10, 400); const left = Math.max(0, (w - labelW - barW) / 2); const barX = left + labelW; const rowH = 30; const barH = 18; ctx.font = '15px system-ui, sans-serif'; ctx.textBaseline = 'middle'; ctx.textAlign = 'right'; const rows = [ ['Kinetic', [[kinetic, kColor]]], ['Potential', [[potential, pColor]]], ['Total', [[kinetic, kColor], [potential, pColor]]], ]; rows.forEach(([label, segments], i) => { const y = 10 + i * rowH; ctx.fillStyle = fg; ctx.fillText(label, barX - 12, y + barH / 2); // outline at full scale, then filled segments ctx.strokeStyle = fg; ctx.globalAlpha = 0.25; ctx.lineWidth = 1; ctx.strokeRect(barX + 0.5, y + 0.5, barW, barH); ctx.globalAlpha = 1; let sx = barX; for (const [value, col] of segments) { const sw = Math.min(value / total, 1) * barW; ctx.fillStyle = col; ctx.fillRect(sx, y, sw, barH); sx += sw; } }); } // Phase plot: q horizontal (lined up with the spring diagram), p vertical. // The axes are fixed so changing k and m visibly reshapes the orbit. const pMax = 3; function drawPhase(canvas, params, trail, q, p) { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const { rest, swing, qToX } = layout(w); const mid = h / 2; const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16); const fg = color('--fg'); const accent = color('--accent'); // axes ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.globalAlpha = 0.5; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(rest - swing - 20, mid); ctx.lineTo(rest + swing + 20, mid); ctx.moveTo(rest, 8); ctx.lineTo(rest, h - 8); ctx.stroke(); ctx.globalAlpha = 1; ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; ctx.fillText('q', rest + swing + 26, mid); ctx.textBaseline = 'top'; ctx.fillText('p', rest + 8, 6); // level curve H = k q0^2 / 2: an ellipse with semi-axes q0 and q0 sqrt(k m) const { k, m, q0 } = params; const rx = Math.abs(q0) * swing; const ry = Math.abs(pToY(Math.abs(q0) * Math.sqrt(k * m)) - mid); ctx.strokeStyle = fg; ctx.globalAlpha = 0.35; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.ellipse(rest, mid, rx, ry, 0, 0, 2 * Math.PI); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; // trail, then the current state ctx.strokeStyle = accent; ctx.lineWidth = 2; ctx.beginPath(); trail.forEach(([tq, tp], i) => { if (i === 0) ctx.moveTo(qToX(tq), pToY(tp)); else ctx.lineTo(qToX(tq), pToY(tp)); }); ctx.stroke(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(qToX(q), pToY(p), 6, 0, 2 * Math.PI); ctx.fill(); } // Page 1: the spring and its equations of motion const springParams = { k: 6.25, m: 1, q0: 0.6 }; const spring = createSpring({ canvas: document.getElementById('spring-canvas'), button: document.getElementById('spring-toggle'), params: springParams, }); // Page 2: the same spring, with energy bars. Slower and without the arrows, // so the moving bars are the only thing to watch. const energyBars = document.getElementById('energy-bars'); const energy = createSpring({ canvas: document.getElementById('energy-canvas'), button: document.getElementById('energy-toggle'), params: springParams, speed: 0.5, onDraw: (q, p) => drawEnergyBars(energyBars, springParams, q, p), }); // Page 4: phase space, with adjustable q0, k and m const phaseParams = { k: 4, m: 1, q0: 0.6 }; const phaseCanvas = document.getElementById('phase-canvas'); const phasePlot = document.getElementById('phase-plot'); const q0Slider = document.getElementById('phase-q0'); let phaseTrail = []; const phase = createSpring({ canvas: phaseCanvas, button: document.getElementById('phase-toggle'), params: phaseParams, labels: ['q', 'p', 'k', 'q0'], pScale: 1 / pMax, onDraw: (q, p) => { phaseTrail.push([q, p]); if (phaseTrail.length > 2000) phaseTrail.shift(); drawPhase(phasePlot, phaseParams, phaseTrail, q, p); alignSlider(); }, }); // Stretch the q0 slider so its thumb sits directly under q0 on the diagram. function alignSlider() { const { rest, swing } = layout(phaseCanvas.clientWidth); const thumb = 16; q0Slider.style.width = `${2 * swing + thumb}px`; q0Slider.style.marginLeft = `${rest - swing - thumb / 2}px`; } for (const name of ['q0', 'k', 'm']) { const input = document.getElementById(`phase-${name}`); const output = document.getElementById(`phase-${name}-value`); input.value = phaseParams[name]; output.textContent = phaseParams[name]; input.addEventListener('input', () => { phaseParams[name] = Number(input.value); output.textContent = input.value; phaseTrail = []; phase.reset(); }); } // Page 5: the pendulum const pendulum = createPendulum({ canvas: document.getElementById('pendulum-canvas'), button: document.getElementById('pendulum-toggle'), params: { m: 1, L: 1, g: 9.8, theta0: 1.0, p0: 0 }, }); // Page 6: pendulum phase space. theta runs across [-pi, pi]; p is fixed at // +/- pendulumPMax, which fits the separatrix at the default parameters // with room for rotations. const pendulumPMax = 12; const pendulumDefaults = { m: 1, L: 1, g: 9.8 }; const pendulumParams = { ...pendulumDefaults, theta0: 0.3, p0: 0 }; const pendulumPresets = { small: { theta0: 0.3, p0: 0 }, large: { theta0: 2.5, p0: 0 }, top: { theta0: 3.1, p0: 0 }, rotation: { theta0: 0, p0: 8 }, balanced: { theta0: Math.PI - 1e-6, p0: 0 }, // a tiny nudge, so it falls after a few seconds rest: { theta0: 0, p0: 0 }, }; const pendulumPlot = document.getElementById('pendulum-plot'); let pendulumTrail = []; const pendulumPhase = createPendulum({ canvas: document.getElementById('pendulum-phase-canvas'), button: document.getElementById('pendulum-phase-toggle'), params: pendulumParams, labels: ['theta', 'p'], centered: true, pScale: 60 / pendulumPMax, onDraw: (theta, p) => { pendulumTrail.push([theta, p]); if (pendulumTrail.length > 3000) pendulumTrail.shift(); drawPendulumPhase(pendulumPlot, pendulumParams, pendulumTrail, theta, p); }, }); function drawPendulumPhase(canvas, params, trail, theta, p) { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const { m, L, g } = params; const halfW = Math.min(w / 2 - 30, 300); const cx = w / 2; const mid = h / 2; const thetaToX = (t) => cx + (t / Math.PI) * halfW; const pToY = (pv) => mid - (pv / pendulumPMax) * (h / 2 - 16); const fg = color('--fg'); const accent = color('--accent'); ctx.save(); ctx.beginPath(); ctx.rect(cx - halfW, 0, 2 * halfW, h); ctx.clip(); // background phase portrait: level curves of H, in units of m g L. // Level 1 is the separatrix between swinging and rotating. const levels = [-0.9, -0.6, -0.2, 0.3, 0.7, 1, 1.5, 2.5, 4]; const n = 300; for (const c of levels) { ctx.strokeStyle = fg; ctx.globalAlpha = c === 1 ? 0.45 : 0.15; ctx.lineWidth = c === 1 ? 1.5 : 1; for (const sign of [1, -1]) { ctx.beginPath(); let drawing = false; for (let i = 0; i <= n; i++) { const t = -Math.PI + (2 * Math.PI * i) / n; // p^2 / (2 m L^2) - m g L cos(t) = c m g L const p2 = 2 * m * L * L * m * g * L * (c + Math.cos(t)); if (p2 < 0) { drawing = false; continue; } const x = thetaToX(t); const y = pToY(sign * Math.sqrt(p2)); if (drawing) ctx.lineTo(x, y); else ctx.moveTo(x, y); drawing = true; } ctx.stroke(); } } ctx.globalAlpha = 1; // trail, broken where theta wraps around ctx.strokeStyle = accent; ctx.lineWidth = 2; ctx.beginPath(); trail.forEach(([tt, tp], i) => { const jump = i > 0 && Math.abs(tt - trail[i - 1][0]) > Math.PI; if (i === 0 || jump) ctx.moveTo(thetaToX(tt), pToY(tp)); else ctx.lineTo(thetaToX(tt), pToY(tp)); }); ctx.stroke(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(thetaToX(theta), pToY(p), 6, 0, 2 * Math.PI); ctx.fill(); ctx.restore(); // axes ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.globalAlpha = 0.5; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(cx - halfW, mid); ctx.lineTo(cx + halfW, mid); ctx.moveTo(cx, 8); ctx.lineTo(cx, h - 8); ctx.stroke(); ctx.globalAlpha = 1; ctx.font = 'italic 18px Georgia, serif'; ctx.textBaseline = 'middle'; ctx.textAlign = 'left'; ctx.fillText('θ', cx + halfW + 6, mid); ctx.textBaseline = 'top'; ctx.fillText('p', cx + 8, 6); ctx.font = '13px system-ui, sans-serif'; ctx.textAlign = 'center'; ctx.fillText('−π', cx - halfW, mid + 6); ctx.fillText('π', cx + halfW, mid + 6); } const pendulumPreset = document.getElementById('pendulum-preset'); const pendulumInputs = ['theta0', 'p0', 'm', 'L', 'g'].map((name) => ({ name, input: document.getElementById(`pendulum-${name}`), output: document.getElementById(`pendulum-${name}-value`), })); function syncPendulumInputs() { for (const { name, input, output } of pendulumInputs) { input.value = pendulumParams[name]; output.textContent = pendulumParams[name].toFixed(2); } } function resetPendulumPhase() { pendulumTrail = []; pendulumPhase.reset(); } for (const { name, input, output } of pendulumInputs) { input.addEventListener('input', () => { pendulumParams[name] = Number(input.value); output.textContent = pendulumParams[name].toFixed(2); pendulumPreset.value = 'custom'; resetPendulumPhase(); }); } // A preset restores the default m, L and g along with its initial state. pendulumPreset.addEventListener('change', () => { const preset = pendulumPresets[pendulumPreset.value]; if (!preset) return; Object.assign(pendulumParams, pendulumDefaults, preset); syncPendulumInputs(); resetPendulumPhase(); }); syncPendulumInputs(); const sims = { spring, energy, phase, pendulum, 'pendulum-phase': pendulumPhase }; const pageIds = [...document.querySelectorAll('.page')].map((el) => el.id); const navPrev = document.getElementById('nav-prev'); const navNext = document.getElementById('nav-next'); function show(id) { document.querySelectorAll('.page').forEach((el) => { el.classList.toggle('active', el.id === id); }); const i = pageIds.indexOf(id); // label each button with a one-word hint of where it goes const hint = (j) => document.getElementById(pageIds[j])?.dataset.hint ?? ''; navPrev.disabled = i === 0; navNext.disabled = i === pageIds.length - 1; navPrev.textContent = `← ${hint(i - 1)}`.trim(); navNext.textContent = `${hint(i + 1)} →`.trim(); document.getElementById('nav-pos').textContent = `${i + 1} / ${pageIds.length}`; for (const [name, sim] of Object.entries(sims)) { if (name === id) sim.draw(); else sim.pause(); } } document.querySelectorAll('[data-tex]').forEach((el) => { katex.render(el.dataset.tex, el, { displayMode: el.tagName === 'DIV' }); }); document.querySelectorAll('[data-solution]').forEach((toggle) => { toggle.addEventListener('click', () => { const solution = document.getElementById(toggle.dataset.solution); solution.hidden = !solution.hidden; toggle.textContent = solution.hidden ? 'Show solution' : 'Hide solution'; }); }); // Pages that start centered: revealing splits them into text and diagram // panels and labels the diagram. const revealLabels = { spring: ['m', 'k', 'q', 'F', 'p'], energy: [], // stays unlabeled, so the bars are the only thing moving pendulum: ['m', 'L', 'theta', 'p', 'g'], }; document.querySelectorAll('[data-reveal]').forEach((button) => { button.addEventListener('click', () => { const id = button.dataset.reveal; const section = document.getElementById(id); button.hidden = true; section.classList.add('split'); section.querySelector('.text').hidden = false; sims[id].setLabels(revealLabels[id]); }); }); // The current page lives in the URL hash, so reloading stays put. function showFromHash() { const id = location.hash.slice(1); show(document.getElementById(id)?.classList.contains('page') ? id : 'landing'); window.scrollTo(0, 0); } window.addEventListener('hashchange', showFromHash); showFromHash(); document.querySelectorAll('[data-goto]').forEach((el) => { el.addEventListener('click', () => { location.hash = el.dataset.goto; }); }); function goToIndex(i) { location.hash = pageIds[Math.max(0, Math.min(pageIds.length - 1, i))]; } function currentIndex() { return pageIds.indexOf(document.querySelector('.page.active').id); } navPrev.addEventListener('click', () => goToIndex(currentIndex() - 1)); navNext.addEventListener('click', () => goToIndex(currentIndex() + 1)); document.addEventListener('keydown', (e) => { if (e.altKey || e.ctrlKey || e.metaKey) return; if (e.target.closest('input, select')) return; // arrow keys belong to the control const target = { ArrowLeft: currentIndex() - 1, ArrowRight: currentIndex() + 1, Home: 0, End: pageIds.length - 1, }[e.key]; if (target === undefined) return; e.preventDefault(); goToIndex(target); });