Using mathjax in an updating sequence in javascript

I have four dynamic variables in my program,

xzero, xone, xtwo, xthree

That represent the coefficients of a cubic function. I want to show the actual equation in the HTML, in the following format:

xthree*x^3+xtwo*x^2+xone*x+xzero=f(x)

but it needs to be able to update with the variables, so I had originally thought that I would do a

document.getElementById("demo").innerHTML = (new equation);

But it seems to me that either mathJax doesn't work in javascript, or that I'm not doing it right. The only alternative solution that I could think of is to make four individual div tags per variable, and update them all, but this seems unnecessarily clunky. Could I get some pointers either way as to how I would fix this?

Answers:

Answer

MathJax automagically renders the document when it is loaded, but not later. Try explicitly requesting re-render:

document.getElementById("demo").innerHTML = "...";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, 'demo']);

EDIT: After some thinking, I figured you could ask for the render in one element, keep it hidden, then copy the finished markup into another, to prevent flicker:

var mathDiv = document.getElementById('math');
var displayDiv = document.getElementById('display');

MathJax.Hub.Queue(["Typeset",MathJax.Hub,"math"]);
MathJax.Hub.Queue(function() {
  var math = MathJax.Hub.getAllJax("MathDiv")[0];
  var i = 1;
  setInterval(function() {
    MathJax.Hub.Queue(["Text", math, "\\int_0^{" + i + "} x dx"]);
    MathJax.Hub.Queue(function() {
      displayDiv.innerHTML = mathDiv.innerHTML;
    });
    i++;
  }, 1000);
});
#math {
  display: none
}
<script type="text/javascript"
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<div id="math">$$$$</div>
<div id="display"></div>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.