Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display MathJax dynamically only when there are delimiters

I have been tweaking with below sample code. The documentation for MathJax isn't very complete. Could someone more experience tell how I should modify the below code so that Tex is only parse when I have specified delimiters like $\alpha$. I would like to make it work like on math.stackexchange.

   <html>
    <head>
    <title>MathJax Dynamic Math Test Page</title>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [["$","$"],["\\(","\\)"]]
        }
      });
    </script>
    <script type="text/javascript"
      src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full">
    </script>

    </head>
    <body>

    <script>
      //
      //  Use a closure to hide the local variables from the
      //  global namespace
      //
      (function () {
        var QUEUE = MathJax.Hub.queue;  // shorthand for the queue
        var math = null;                // the element jax for the math output.

        //
        //  Get the element jax when MathJax has produced it.
        //
        QUEUE.Push(function () {
          math = MathJax.Hub.getAllJax("MathOutput")[0];
        });

        //
        //  The onchange event handler that typesets the
        //  math entered by the user
        //
        window.UpdateMath = function (TeX) {
          QUEUE.Push(["Text",math,"\\displaystyle{"+TeX+"}"]);
        }
      })();
    </script>
    <textarea  id="MathInput" size="50" onkeyup="UpdateMath(this.value)"></textarea>

    <div id="MathOutput">
    You typed: ${}$
    </div>

    </body>
    </html>
like image 570
Mark Avatar asked Oct 28 '11 07:10

Mark


1 Answers

The sample code you posted takes the contents of the MathInput and replaces the first MathJax element with the new "math" from the MathInput. What you want is to Typeset the MathInput and create new MathJax elements for the delimited text. I setup a jsFiddle example here: http://jsfiddle.net/Zky72/2/

The main change is in the UpdateMath function:

 window.UpdateMath = function (TeX) {
    //set the MathOutput HTML
    document.getElementById("MathOutput").innerHTML = TeX;

    //reprocess the MathOutput Element
    MathJax.Hub.Queue(["Typeset",MathJax.Hub,"MathOutput"]);

}
like image 165
Phil McCullick Avatar answered Nov 05 '22 03:11

Phil McCullick