Search code examples
javascriptmathjax

How to left align certain equations in MathJax


So, by default MathJax equations are centered, but I want to left align certain equations. I know how to make ALL equations left aligned with MathJax.Hub.Config, but this is not what I want.

I've tried other code found on the web, such as the following:

<script type="text/javascript">
  MathJax.Hub.Queue(function () {
      MathJax.Hub.Config({displayAlign:"left"});
      MathJax.Hub.Typeset(["leqn"]);
    });
 </script>

then wrapped a div around the equation with an id of leqn, like so:

<div id="leqn">$$e^{\pi i} - 1 = 0$$</div>

This does not work and I don't know enough about MathJax or even JS to have any idea as to what I'm doing wrong. Any ideas?


Solution

  • There's no elegant way for doing this using TeX input. The approach will vary with the use cases. Here you seem to be able to wrap HTML around those equations you want to align to the left. For this you are generally on the right track. Here's what would need fixing:

    • use the correct way of hooking into MathJax's internals
    • have MathJax ignore the relevant equations on the first round of typesetting by adding class="tex2jax_ignore"
    • remove that class, change the configuration, and have MathJax typeset the rest

    Below is one way of doing that.

    • You can configure other class names, see the docs.
    • It's a bit more complicated because of SO's restrictions on external resources in snippets (no query strings allowed so I'm injecting it "manually") -- in your page, just use the window.MathJax part and load it before you load MathJax.js.

          window.MathJax = {
            AuthorInit: function() {
              MathJax.Hub.Register.StartupHook("Begin", function() {
                MathJax.Hub.Queue(function() {
                  var elements = document.getElementsByClassName('tex2jax_ignore');
                  for (var i = 0; i < elements.length; i++) {
                    elements[i].classList.remove('tex2jax_ignore');
                  }
                  MathJax.Hub.Config({
                    displayAlign: "left"
                  });
                  MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
                });
              });
            }
          };
    
          (function(d, script) {
            script = d.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML-full';
            d.getElementsByTagName('head')[0].appendChild(script);
          }(document));
    $$e^{\pi i} - 1 = 0$$
    <span class="tex2jax_ignore">$$e^{\pi i} - 1 = 0$$</span>
    $$e^{\pi i} - 1 = 0$$