Search code examples
javascripthtmlcssmathjax

How to feed output string through MathJax prior to updating innerHTML with it


I know that this has been asked previously but I just can't make a single step towards a functional solution.

I have a big piece of Javascript code that processes some input equation and outputs a step-by-step solution to the equation. So the user inputs the equation into an box, they click a button, and it sets off the events in the code below:

function getInputValue() {
  let inputVal = document.getElementById('myInput').value;
  codeOut = '';
  // Function which appends to codeOut throughout its stages
  UncPropSteps(inputVal);
  document.getElementById('MathOutput').innerHTML = codeOut;
}

This correctly assigns the output stages to that 'MathOutput' box, but without any of the MathJax formatting since it has already completed its initial sweep of the page. I have tried other functions I've found online to refresh specific elements, I've tried MathJax.Hub.Queue(["Typeset",MathJax.Hub,"MathOutput"]);, but I just can't get MathJax to ever attempt a refresh. The output can potentially end up extending to quite a lot of lines, so trying to find a LaTeX -> Image -> URL -> src pathway would be challenging too. Can anyone recommend a reliable method for passing codeOut through MathJax before assigning it to the innerHTML?

The input code is below, if it's relevant.

<div class="wrapper">
  <input type="text" placeholder="Type something..." id="myInput" size="70">
  <button class="button" onclick="getInputValue()">Propagate!</button>
  <button class="button" onclick="clearBox()">Clear</button>
  <p id="MathOutput">[Numeric solution will come out here!]</p>
</div>

Solution

  • According to the official documentation, if you have a page with dynamic content like in your case, you need to use the typeset

    Have you tried MathJax.typeset() ?

    If you need to do this asynchronously

    MathJax.typesetPromise().then(() => {
      // modify the DOM here
      MathJax.typesetPromise();
    }).catch((err) => console.log(err.message));
    

    Additional info here