Search code examples
javascriptmathjax

how to toggle MathJax render vs code with javascript?


How can I toggle the display of a MathJax equation between its rendered view and plain text/code view using javascript?

For example, How can I get the button in the example below to toggle the equation between displaying this:

$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$

and the equation that renders when you run the snippet?

var btn = document.getElementById("math-toggle");

btn.onclick = function(event) { 
  // Toggle Math rendering here using MathJax API?
  alert("moo!"); 
};
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>MathJax example</title>
  <script type="text/javascript" async
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/latest.js?config=TeX-MML-AM_CHTML" async>
</script>
</head>
<body>
<button id="math-toggle">Toggle Math</button>

<p>
Equation:  $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
</p>
</body>
</html>


Solution

  • One way (using MathJax APIs) would be to use the PlainSource output and re-render.

    Depending on the situation, it might be easier to keep track of this in the application (e.g., just grab the contents of the script tag that MathJax creates).

    Since the delimiters used for TeX only come into play at the pre-processing stage (and are user configurable) additional logic is needed to track that.

    var btn = document.getElementById("math-toggle");
    
    btn.onclick = function(event) {
      if (!btn.checked) {
        MathJax.Hub.Queue(["setRenderer", MathJax.Hub, "CommonHTML"]);
        MathJax.Hub.Queue(["Rerender", MathJax.Hub]);
      } else {
        MathJax.Hub.Queue(["setRenderer", MathJax.Hub, "PlainSource"]);
        MathJax.Hub.Queue(["Rerender", MathJax.Hub]);
    
      }
    };
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>MathJax example</title>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/latest.js?config=TeX-MML-AM_CHTML">
      </script>
    </head>
    
    <body>
      <input id="math-toggle" type="checkbox"  name="mathjax-switch" >
      <label id="mathjax-switch">Replace with plain text source</label>
      <p>
        Equation: $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
      </p>
    </body>
    
    </html>