Mathjax is a cross-browser JavaScript display engine that provides support for mathematical notation in web browers.

Specifically, Mathjax enables LaTeX syntax to write math equations Markdown and show on Github Pages.

The support for TeX and LaTeX in MathJax consists of two parts

  1. the tex2jax processor

    It looks for mathmatics within your web page (indicated by math delimiters like $$...$$) and marks the mathematics for later processing by MathJax.

  2. the TeX input processor

    It converts the TeX notation into MathJax’s internal format (which is essentially MathML).

The current version, as of 2023 when this blog was written, is V3.0. See official documents here.

The latest document for V3 may not be stable, some parts are missing. Refer to the document for V2 for a complete version.

The configuration, loading, and startup processes for MathJax version 3 are different from those of version 2 in a number of ways.

Where version 2 had several different methods for configuring MathJax, version 3 streamlines the process and has only one, as described below.

In version 2, you always loaded MathJax.js, and added a config=... parameter to provide a combined configuration file, but in version 3 you load one of several different files, depending on your needs (so you can avoid multiple file transfers, and also use MathJax synchronously, which was not possible in version 2).

Version 3

In-line Configuration for Mathjax

Q: Where to put the configuration data?
A: Add the following codes to the end of the file _layouts/base.html. This loads MathJax automatically for all posts.

The easiest way to configure MathJax is to place the MathJax object in a <script> tag just before the script that loads MathJax itself.

In-line configuration puts the configuration options within the web page itself. The use of in-line configuration with MathJax requires two separate <script> tags:

  • one for specifying the configuration settings and
  • one for loading of MathJax.

Because MathJax starts its configuration process as soon as it is loaded, the configuration script must come before the script tag that loads MathJax.jsitself.

<!-- inline config -->
<script>
  MathJax = {
    tex: {
      inlineMath: [   // start/end delimiter pairs for in-line math
        ['$', '$'], 
        ['\\(', '\\)'] 
      ],
      displayMath: [  // start/end delimiter pairs for display math
        ['$$', '$$'],
        ['\\[', '\\]']
      ],
      processEscapes: true, // use \$ to produce a literal dollar sign
      macros: {  // define custom TeX macros
      	RR: "{\\bf R}",
      	bold: ["{\\bf #1}", 1],
        indep: "{\\perp \\!\\!\\! \\perp}",
    	},
      tags: 'ams', // should be 'ams', 'none', or 'all'
      packages: {'[-]': ['noundefined', 'autoload'], '[+]': ['enclose']}, 
    },

    svg: {
      fontCache: 'global'
  	},
  };
</script>

<!-- load MathJax -->
<script type="text/javascript" id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>

The first script defines a global object named MathJax that contains configuration data for the various components of MathJax.

The MathJax has to be put before the script that loads MathJax itself.

The MathJax object defined above means:

  • tex to configure the TeX input processor component. Check HERE for a full list of options. Commonly used options are:

    • inlineMath allows you to use single dollar signs ($) as in-line math delimiters, in addition to the usual \\(...\\).

      LaTeX uses brackets and parentheses as math delimiters; TeX use dollar signs. By default, MathJax supports brackets and parentheses, but not dollar signs. You need to enable them if you want to use TeX delimiters.

      Note that when you use brackets and prarentheses, you need double backslashes (\\(...\\) or \\[...\\]) to escape backslashes.

    • displayMath an array of pairs of strings that are to be used as delimiters for displayed/block equations.

      MathJax processes all environments when wrapped inside math delimiters, even those like \begin{equation}...\end{equation} that are supposed to be used to initiate math mode.

      This feature is useful to enable Typora preview of equations while make sure MathJax can render it correctly.

      Typora doesn’t support LaTeX delimiters (brackets and parentheses). In order to ensure compatibility, use double signs and add one empty line before and after for displayed eqns.

    • The default for processEscapes has changed from false in version 2 to true in version 3.

      • When set to true, you may use \$ to represent a literal dollar sign, rather than using it as a math delimiter, and \\ to represent a literal backslash (so that you can use \\\$ to get a literal \$ or \\$...$ to get a backslash just before in-line math).

      • When false, \$ will not be altered, and its dollar sign may be considered part of a math delimiter. Typically this is set to true if you enable the $ ... $ in-line delimiters, so you can type \$ and MathJax will convert it to a regular dollar sign in the rendered document.

    • macros allows you to define your own TeX commands.

      Similar to \def, \newcommand, \renewcommand, \newenvironment … which allow you to create your own macros and environments.

      macro is given as a name: value pair, where the name is the name of the control sequence (without the backslash) that you are defining, and value is either the replacement string for the macro (when there are no arguments) or an array consisting of the replacement string followed by the number of arguments for the macro and, optionally, default values for optional arguments.

      Note that the replacement string is given as a JavaScript string literal, and the backslash (\) has special meaning in javascript strings. So to get an actual backslash in the string you must double it (\\ this escapes the backslash), as in the examples above.

      Just include your macro definitions in the macros section of the tex blocks of your configuration. The code above would define

      • \RR to produce a bold-faced “R”, and
      • \bold{...} to put its argument into bold face,
      • \indep ($\indep$) to show double perpendicular sign to represent independence,
    • tags: 'ams' tells the TeX input processor to use the AMSmath package numbering rules.
      • Only certain environments (\begin{equation}) produce numbered equations, as they would be in LaTeX.
      • tags: 'none': auto-numbering was not performed.
      • tags: 'all': numbering for every displayed equation.
    • packages: ['base'] lists the names of the packages that should be initialized by the TeX input processor.
      • add new packages using '[+]': ['enclose', ...].
      • remove packages from the default list using '[-]': ['noundefined', 'autoload'].
  • svg output component specifies a global font cache for all expressions on the page, rather than a separate cache for each expression on the page.

    • svg is a Scalable Vector Graphics; it is scalable, high quality at any resolution.
    • Other benifts of using svg: It won’t get pixelated at different screen sizes, like a raster image would.

Now that you have configured MathJax, you can then load the MathJax component file that you want to use. Here, we use the following.

<script type="text/javascript" id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>

More MathJax custom macros:


Using a Local File for Configuration

If you are using the same MathJax configuration over multiple pages, you may find it convenient to store your configuration in a separate JavaScript file that you load into the page. For example, you could create a file called mathjax-config.js that contains

window.MathJax = {
  tex: {
    inlineMath: [['$', '$'], ['\\(', '\\)']]
  },
  svg: {
    fontCache: 'global'
  }
};

and then use

<script src="mathjax-config.js" defer></script>
<script type="text/javascript" id="MathJax-script" defer
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js">
</script>

to first load your configuration file, and then load the tex-svg component from the jsdelivr CDN.

Note that here we use the defer attribute on both scripts so that they will execute in order, but still not block the rest of the page while the files are being downloaded to the browser.

If the async attribute were used, there is no guarantee that the configuration would run first, and so you could get instances where MathJax doesn’t get properly configured, and they would seem to occur randomly.

The src attribute in<script> specifies the URL of the external MathJax configuration file (mathjax-config.js). In Jekyll websites, you need to specify the relative path using:

<script src="{{site.baseurl}}/assets/js/mathjax-config.js" defer></script>

It is convenient to define macros for different font faces, e.g., caligraphic, blackboard face …

The following is an example for letter A. You can define accordingly for all other letters.

window.MathJax = {
  tex: {
    macros: {
      indep: "{\\perp \\!\\!\\! \\perp}",
      bA: "\\boldsymbol{A}",  // bold face capital letter 英文字母
      ba: "\\boldsymbol{a}",  // bold face small letter
      Acal: "\\mathcal{A}",   // math calligraphic font 花体      
      A: "\\mathbb{A}",  // blackboard face 黑板粗体
      bDelta: "\\boldsymbol{\\Delta}",  // uppercase Greeks 希腊字母
      bbeta: "\\boldsymbol{\\beta}",    // lowercase Greeks
    }
  }
};

After defining the macros, now you can do

  • $\bA$ ($\bA$ bold face $A$, often used for denoting matrices)
  • $\ba$ ($\ba$ bold face $a$, often used for denoting vectors)
  • $\Fcal$ ($\Fcal$ caligraphic $F$ for information set)
  • $\E$ ($\E$ blackboard $E$ for expectations)
  • $\bDelta$ ($\bDelta$ bold $\Delta$)
  • $\bbeta$ ($\bbeta$ bold $\beta$)

Locations which require MathJax support:

  • Software: Typora, VS Code
  • Website: Personal website, metrics notes

General Guidelines

  1. Since MathJax renders for the web and TeX is a print layout engine, there are natural limitations of which parts of TeX can be supported in a reasonable way.

    By default, the tex2jax preprocessor defines the LaTeX math delimiters, which are \(...\) for in-line math, and \[...\] for displayed equations.

    It also defines the TeX delimiters $$...$$ for displayed equations, but it does not define $...$ as in-line math delimiters. If you want to use $...$ as in-line math delimiter, you need to configure it in the tex component.

    The default settings are as follows.

     MathJax = {
       tex: {
         inlineMath: [   // start/end delimiter pairs for in-line math
           ['$', '$'], 
           ['\\(', '\\)']
         ],
         displayMath: [  // start/end delimiter pairs for display math
           ['$$', '$$'],
           ['\\[', '\\]']
         ],
         processEscapes: true, // use \$ to produce a literal dollar sign
       },
     };
    

    This is an example of inline equations: \(y = x’\beta + \varepsilon \) (\\(y = x'\beta + \varepsilon \\)).

    This is an example of block equations. \[ y = x’\beta + \varepsilon \]

     \\[
       y = x'\beta + \varepsilon
     \\]
    

    Note that you need to use double backslash followed by brackets or parentheses. The only problem with that is some markdown editor won’t provide a preview for equations using the default delimiter for TeX.

  2. Must add a blank line before and after a block equation so that it is rendered correctly.

  3. When print | vertical bar in inline equations, must use \vert otherwise, will be recognized as a table column separator.


FAQ

Font

Not all fonts work as they should with MathJax math. E.g., \mathbf does not work for greeks.

  • $\mathbf{\beta}$ (\mathbf{\beta}) not showing bold font as expected.

    $\boldsymbol{\beta}$ (\boldsymbol{\beta}) works

  • $\mathbf{B}$ (\mathbf{B} or \bf B) bold font works for regular text

Q: What is tex2jax for?

Some times you see settings for tex2jax

tex2jax: {
  inlineMath: [ ['$','$'], ['\\(','\\)'] ],
  processEscapes: true,
}

This is obsolete in MathJax V3. In version 2, MathJax used preprocessors, tex2jax, to locate the mathematics in the page and prepare it for the input jax. In version 3, these have been folded into their respective input jax. That means that you don’t load them separately, and the configuration options of the preprocessor and input jax have been combined. For example, the tex2jax and TeX options now both occur in the tex configuration block.

Q: How to print curly braces?
A: You have to escape the backslash because there seems to be 2 levels of interpretation : jekyll then mathjax. So you need to escape the backslash from Jekyll so it renders for Mathjax to escape the bracket :

$ \\{ 2*3 \\} $ -> {2*3} 

Alternatively , you can use \lbrace and \rbrace.

Note that in block equations, you do NOT need to double escape (one backslash would do), e.g.,

$$
S = \{0, 2, 4, 6, 8, 10\}
$$
\[S = \{0, 2, 4, 6, 8, 10\}\]

Cross References to Eqns

Refer to an eqn on the same page

  1. At the eqn, add \tag{} and label{}

    \tag is the number that shows at the end of the equation. Note that \tag will interrupt the numbering continuity within a document. Do not use \tag to insert numbers. Use this to add labels like (*), symbols to denote equations.

    \label is the internal identifier that you use for cross references.

    \label{myequation} \tag{4.1}  
    
  2. Refer to the eqn using simple html links <a href="">.

    "<a href="http://www.mysite.com/mypage#myequation"> 4.1 </a>"
    

    Or using latex command:

    • \ref{myequation} (this does not add parentheses, need to add parentheses manually).
    • \eqref{myequation} (this adds parenthese around the label automatically) [Recommended ✅]
    • Note that references can come before the corresponding formula as well as after them.
    See Eq (\ref{myequation}) or Eq \eqref{myequation}.
    

Example

Distributive law for multiplication (from product of sums to double sums).

\[\begin{equation} \label{multiplication} \sum_{i=1}^k a_i \cdot \sum_{j=1}^m b_j = \sum_{i=1}^k \left(\sum_{j=1}^m a_ib_j\right) \end{equation}\]
\begin{equation} \label{multiplication}
\sum_{i=1}^k a_i \cdot \sum_{j=1}^m b_j = \sum_{i=1}^k \left(\sum_{j=1}^m a_ib_j\right)
\end{equation}

Refer to the equation

  • using Eq \eqref{multiplication} or Eq $\eqref{multiplication}$: Eq $\eqref{multiplication}$.
  • using Eq (\ref{multiplication}) or Eq ($\ref{multiplication}$): Eq ($\ref{multiplication}$).

Note that \ref and \eqref can be either enclosed in $...$ or not, depending on the editor you use.

  • Typora only supports the versions enclosed with dollar signs, i.e., $\ref{}$ and $\eqref{}$
  • VS Code supports both.
  • Browser support both.

What does \tag* do?

  • \tag{2.1} puts 2.1 in parentheses.
  • \tag*{2.1} suppress the parentheses.

See examples as follows.

With parentheses: \(v = a\cdot t \tag{2.1}\)

v = a\cdot t \tag{2.1}

Vs.

Without parentheses: \(d = \frac {1}{2}\cdot a \cdot t^2 \tag*{2.2}\)

d = \frac {1}{2}\cdot a \cdot t^2 \tag*{2.2}

Refer to an equation in a different page with Mathjax


Automatic equation numbering

The TeX input processing in MathJax can be configured to add equation numbers to displayed equations automatically. This functionality is turned off by default, but it is easy to configure MathJax to produce automatic equation numbers by adding:

MathJax = {
  tex: {
    tags: 'ams'  // should be 'ams', 'none', or 'all'
  },
};

to tell the TeX input processor to use the AMS numbering rules.

With the configuration tag:'ams' you need to wrap the equation with \begin{equation} and \end{equation} in order to add numbering.

The unstarred versions produce equation numbers (when tags is set to 'ams') and the starred ones (\begin{equation*} ) don’t.

You can use \notag or \nonumber to prevent individual equations from being numbered, and \tag{} can be used to override the usual equation number with your own symbol instead (or to add an equation tag even when automatic numbering is off).

tags: 'all': every displayed equation will get a number, regardless of the environment used.

Numbered equation:

\begin{equation} E = mc^2 \end{equation}

\begin{equation}
  E = mc^2
\end{equation}

Unnumbered equation:

\[\begin{equation*} e^{\pi i} + 1 = 0 \end{equation*}\]
$$
\begin{equation*}
   e^{\pi i} + 1 = 0
\end{equation*}
$$

 

  • Note that for unnumbered equations, the \begin{equation*}...\end{equation*} needs to be enclosed in $$ so that it is rendered correctly.

Numbered equation again.

\begin{equation} \int_0^\infty \frac{x^3}{e^x-1}\,dx = \frac{\pi^4}{15} \label{eq:sample} \end{equation}

\begin{equation}
  \int_0^\infty \frac{x^3}{e^x-1}\,dx = \frac{\pi^4}{15}
  \label{eq:sample}
\end{equation}

See Eq \eqref{eq:sample} (\eqref{eq:sample}) for an integral example.


Useful Tricks Typesetting Eqns

Color eqns

Must enclose the part you want to color in braces {...}, otherwise everything behind the \color will be colored.

{\color{red} x} + {\color{blue} y}

The code show a formula as follows

\[{\color{red} x} + {\color{blue} y}.\]

Curly braces $\\{Z_t\\}$ have to use double backslashes. First escape the backslash from Jekyll, then mathjax.


QED at the End of Equations

Several options you can choose from.

  1. Use \tag*{\(\blacksquare\)}.
     $$
     e^{x+y}=e^xe^y. \tag*{\(\blacksquare\)}
     $$
    
    \[e^{x+y}=e^xe^y. \tag*{\(\blacksquare\)}\]

    Multi-lined eqn: Use \begin{align*} and put \tag*{\(\blacksquare\)} at the end of the last equality, then close the environment with \end{align*}.

     $$
       \begin{align*}
       \mathbb{E}(Y) &= \sum_j y_j P(Y=y_j)  \\
       &= \sum_j y_j \left[P(Y=y_j|X_1)P(X_1) + P(Y=y_j|X_2)P(X_2) + \cdots + P(Y=y_j|X_n)P(X_n) \right] \\
       &= \sum_j y_j \left[ \sum_{i} P(Y=y_j | X_i) P(X_i) \right] \\
       &= \sum_i \left[\sum_j y_j\,P(Y=y_j | X_i)\right] P(X_i) \\
       &= \sum_i \mathbb E\left[Y|X_i\right] P(X_i) \\
       &= \mathbb{E}\left[\mathbb{E}(Y|X)\right] \tag*{\(\blacksquare\)}
       \end{align*}
     $$
    
    \[\begin{align*} \mathbb{E}(Y) &= \sum_j y_j P(Y=y_j) \\ &= \sum_j y_j \left[P(Y=y_j|X_1)P(X_1) + P(Y=y_j|X_2)P(X_2) + \cdots + P(Y=y_j|X_n)P(X_n) \right] \\ &= \sum_j y_j \left[ \sum_{i} P(Y=y_j | X_i) P(X_i) \right] \\ &= \sum_i \left[\sum_j y_j\,P(Y=y_j | X_i)\right] P(X_i) \\ &= \sum_i \mathbb E\left[Y|X_i\right] P(X_i) \\ &= \mathbb{E}\left[\mathbb{E}(Y|X)\right] \tag*{\(\blacksquare\)} \end{align*}\]
  2. Use \tag*{\(\square\)} for white squares.
     $$
     e^{x+y}=e^xe^y. \tag*{\(\square\)}
     $$
    
    \[e^{x+y}=e^xe^y. \tag*{\(\square\)}\]
  3. Use margin-top:-2em; float:right to set the alignment to float to the right and move upward so that it is in the same line as the equation block.
     $$
     \begin{aligned}
     f(x) &\approx f(0) + f'(0)(x-0) \\
     &= \ln(1) + 1\cdot x  \\
     &= x.
     \end{aligned}
     $$
     <span style='margin-top:-2em; float:right'>$\square$</span>
    

    qed If the equation is long, don’t need to float to the right. The $\square$ will append to the end of the equation. You can add \quad to add whitespaces if needed.

    • \begin{aligned}[b] option [b]</> is needed as we need it to align at the bottom.

      $$
      \begin{aligned}[b]
      P(r_t>0) &= P(\mu+e_t>0) \\
      &= P(e_t>-\mu) \quad\quad\quad (\sigma>0, \text{dividing by a pos. number, inequality unchanged}) \\
      &= P\left( \frac{e_t}{\sigma} > -\frac{\mu}{\sigma}\right) \quad\;\; e_t\sim N(0, \sigma^2), \text{ then } \frac{e_t}{\sigma}\sim N(0,1) \\
      &= P \left( \frac{e_t}{\sigma} < \frac{\mu}{\sigma} \right) \\
      &= \Phi \left(\frac{\mu}{\sigma} \right) 
      \end{aligned}  
      \square
      $$
      

    qed2


Dollar sign

In text mode: $

  • \$ works when processEscapes is enabled.

    MathJax.Hub.Config({
      tex2jax: {
        processEscapes: true
      }
    });
    
  • \\$ always works. You will need to escape the \ in Jekyll.

In math mode: $\$$ (use double back slash to print a dollar sign in math environment)


References:

  1. https://docs.mathjax.org/en/latest/web/configuration.html
  2. https://docs.mathjax.org/en/latest/input/tex/extensions/newcommand.html
  3. Automatic numbering: https://docs.mathjax.org/en/latest/input/tex/eqnumbers.html#automatic-equation-numbering
  4. https://hw311.me/en/jekyll/2019/01/23/support-latex-in-jekyll-blog/
  5. mathjax.html settings: https://github.com/vladislav-morozov/econometrics-heterogeneity/blob/e0da13858c1b54da58294b887bd8504c4b6bf2a4/src/themes/mathjax.html#L11