How do I dynamically change the math string of a particular MathJax (v3.2.0) math item and update its rendering?
The following approach seems to work, but it feels too low-level. I'm worried there are gotchas with this approach, or that a better way exists.
(async() => {
await MathJax.typesetPromise();
const mathDiv = document.getElementById('math');
const [mathItem] = MathJax.startup.document.getMathItemsWithin(mathDiv);
const mathStrings = [
'e^{jx} = \\cos x + j \\sin x',
'\\hat{f}(\\omega) \\stackrel{\\mathrm{def}}{=} \\frac{1}{\\sqrt{2\\pi}} \\int_{-\\infty}^{\\infty} f(t)e^{-j\\omega t} dt',
];
for (let i = 1; true; ++i) {
await new Promise((resolve) => setTimeout(resolve, 2000));
mathItem.reset();
mathItem.math = mathStrings[i % mathStrings.length];
mathItem.render(MathJax.startup.document);
document.getElementById('intro').textContent = `After update #${i}:`;
}
})();
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
<span id="intro">Before update:</span><div id="math">\[\text{placeholder}\]</div>
I would say the documentation is pretty clear here: https://docs.mathjax.org/en/latest/web/typeset.html#updating-previously-typeset-content
For simplest possible most concise solution, go with:
const mathDiv = document.getElementById('math');
await MathJax.startup.promise // make sure initial typesetting has taken place
MathJax.typesetClear([mathDiv]) // clear MathJax awareness of this element
await MathJax.typesetPromise([mathDiv]) // typeset anew
Change await for Promise-style handling if desired and add try, catch as desired to handle errors.