MathJax - Documentation

What is MathJax?

MathJax is a JavaScript display engine for mathematics that works in all modern browsers. It allows you to include mathematical notation in your web pages using LaTeX, MathML, and AsciiMath markup. Instead of relying on images or browser plugins, MathJax renders equations directly within the browser, resulting in high-quality, scalable output that adapts to the user’s screen resolution and preferences. This makes it ideal for websites, blogs, and online learning platforms that need to display mathematical formulas.

Why use MathJax?

Using MathJax offers several key advantages:

Setting up MathJax

Including MathJax in your web page is straightforward. The most common method is to include a script tag in the <head> section of your HTML document, pointing to a Content Delivery Network (CDN):

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

This line fetches the MathJax library from a CDN. You can customize this URL to include additional configurations or to load different components of MathJax (e.g., support for other input languages). Refer to the official MathJax documentation for advanced configuration options. Once included, MathJax automatically processes any mathematical expressions enclosed in specific delimiters.

Basic MathJax Syntax

MathJax primarily uses LaTeX syntax to render equations. This is a powerful and widely used typesetting system for mathematics. Here are some basic examples:

This is just a small subset of the available LaTeX commands. The MathJax documentation provides a comprehensive reference for all available commands and features.

Basic Math Formulas

Inline and Display Formulas

MathJax supports two main modes for rendering mathematical formulas: inline and display.

Greek Letters

Greek letters are rendered using a backslash followed by the letter’s name. For example:

A complete list of Greek letters and their LaTeX commands can be found in the MathJax documentation.

Superscripts and Subscripts

Superscripts and subscripts are created using the ^ and _ characters, respectively. For example:

To create more complex superscripts or subscripts involving multiple characters, enclose them in curly braces {}. For example, $x^{y+z}$ renders as \(x^{y+z}\).

Fractions

Fractions are created using the \frac{numerator}{denominator} command. For example:

Roots

Square roots are created using the \sqrt{expression} command. For example:

For higher-order roots, use \sqrt[n]{expression}, where n is the root’s order. For example: $\sqrt[3]{8}$ renders as \(\sqrt[3]{8}\).

Sums and Integrals

Sums are created using \sum, and integrals are created using \int. Limits are specified using subscripts and superscripts. For example:

Limits

Limits are created using \lim. For example:

Matrices

Matrices are created using the \begin{matrix} ... \end{matrix} environment. Rows are separated by \\, and columns are separated by &. For example:

$$
\begin{matrix}
a & b \\
c & d
\end{matrix}
$$

renders as:

\[ \begin{matrix} a & b \\ c & d \end{matrix} \]

Different matrix types (like pmatrix, bmatrix, Bmatrix, vmatrix, Vmatrix) provide different delimiters. Consult the MathJax documentation for details.

Advanced Math Formulas

Derivatives and Integrals

MathJax provides comprehensive support for expressing derivatives and integrals of varying complexity.

Vectors and Matrices

Beyond the basic matrix notation, MathJax supports more advanced vector and matrix operations.

Sets and Logic

MathJax provides the necessary symbols and environments for expressing set theory and logical concepts.

Differential Equations

Differential equations, both ordinary and partial, can be effectively expressed using MathJax.

Special Functions

MathJax supports a wide range of special functions commonly used in mathematics, physics, and engineering. These functions are typically represented using their standard LaTeX commands. Examples include:

Refer to the MathJax documentation and relevant LaTeX resources for a complete list and detailed usage instructions for special functions.

MathJax Extensions

AMSmath Package

The AMSmath package is a powerful extension that provides numerous functionalities for typesetting mathematics, significantly enhancing MathJax’s capabilities beyond basic LaTeX. It’s automatically loaded in many MathJax configurations, but you might need to explicitly enable it depending on your setup. Key features include:

mhchem Package

The mhchem package is invaluable for rendering chemical formulas and equations with accuracy and clarity. It needs to be explicitly enabled in your MathJax configuration. Key features include:

physics Package

The physics package significantly enhances MathJax’s ability to render physics-related expressions, simplifying the typesetting of common physics notations. Like mhchem, explicit configuration is usually required. Key features:

Extending MathJax with Custom Macros

MathJax allows you to extend its functionality by defining custom macros using LaTeX’s \newcommand and \renewcommand commands. This is particularly useful for creating shortcuts for frequently used expressions or notations specific to your application.

To define custom macros, you can either include them directly in your MathJax configuration or, for larger sets of macros, create a separate .js file with your definitions and load it using a <script> tag.

Example (within MathJax configuration):

MathJax = {
  tex: {
    macros: {
      mymacro: ["\\frac{#1}{#2}", 2], // Defines a macro for fractions
      myconstant: "\\pi"             // Defines a macro for pi
    }
  }
};

Then, in your text, you can use \mymacro{a}{b} to produce \(\mymacro{a}{b}\) and \myconstant to produce \(\myconstant\). Remember that macro definitions need to be valid LaTeX. Complex macros may require careful escaping of special characters.

Typesetting and Formatting

Font Styles and Sizes

MathJax inherits its font handling from LaTeX, offering a range of styles and sizes for mathematical expressions. While automatic sizing is generally effective, you can exert more control using specific LaTeX commands:

Spacing and Alignment

Precise spacing and alignment are crucial for readability in mathematical expressions. MathJax provides several mechanisms to achieve this:

Color and Style

While MathJax doesn’t directly support color changes via simple inline commands within mathematical expressions in the same way that HTML does, you can use CSS to style the output. Directly styling the output using CSS is generally discouraged since it can conflict with updates and changes to MathJax’s styles. Instead, consider using MathJax’s configuration options or extensions for more manageable styling.

Customizing the Appearance of Equations

For significant customization beyond what’s offered by built-in features and extensions, more advanced techniques might be required.

Remember that extensive customization can make your content less portable and harder to maintain. Always strive for a balance between visual appeal and the robustness and maintainability of your code.

Troubleshooting and Debugging

Common Errors and Solutions

Several common issues arise when working with MathJax. Here are some frequent problems and their solutions:

Debugging MathJax Code

Debugging MathJax code often involves examining the rendered output and looking for clues in the browser’s developer console.

Troubleshooting Browser Compatibility

MathJax generally offers excellent browser compatibility, but minor differences or issues might still occur across different browsers or browser versions.

Accessibility and Inclusivity

Screen Reader Compatibility

MathJax’s strength lies in its accessibility features, particularly its support for screen readers. However, optimal screen reader compatibility requires careful consideration of several factors:

Semantic HTML and MathJax

Using semantic HTML alongside MathJax significantly improves accessibility. Instead of simply inserting equations into your content using only the MathJax delimiters, place the equations within appropriate HTML elements to establish their role in the document structure.

Best Practices for Accessible Math

By adhering to these principles, you can create mathematical content that is accessible and inclusive for all users, regardless of their abilities. Regular testing and feedback are key to achieving optimal accessibility.

Integrating MathJax into Websites

Using MathJax with HTML

The simplest way to integrate MathJax into a website is by directly including the MathJax script in your HTML file. This method is suitable for basic websites or those without complex JavaScript frameworks.

  1. Include the script: Add a <script> tag within the <head> section of your HTML, pointing to the MathJax CDN:

    <script type="text/javascript" async
      src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
    </script>
  2. Write your equations: Enclose your mathematical expressions within dollar signs ($...$ for inline, $$...$$ for display) in your HTML content. Ensure the equations are within the <body> of your HTML. Example:

    <p>The Pythagorean theorem is expressed as $a^2 + b^2 = c^2$.</p>
  3. Configuration (optional): For more advanced configurations (e.g., loading specific extensions, customizing rendering), you can include a <script> tag before the MathJax CDN script to define a MathJax object with your configuration settings. See the MathJax documentation for details on configuration options.

Using MathJax with JavaScript Frameworks (React, Angular, Vue)

Integrating MathJax with popular JavaScript frameworks like React, Angular, and Vue requires a slightly different approach to ensure proper rendering within the framework’s lifecycle.

Regardless of the framework, ensure that MathJax is loaded before attempting to render equations. Properly handling the component’s lifecycle (mounting and updating) is crucial for avoiding rendering errors and preventing conflicts with the framework’s rendering process.

Server-Side Rendering with MathJax

Server-side rendering (SSR) with MathJax is essential for improving SEO and initial load time, particularly for websites that heavily feature mathematical content. This process renders the equations on the server before sending the fully rendered HTML to the client’s browser.

Several approaches exist for SSR:

The choice between these approaches depends on factors like your existing infrastructure, scaling requirements, and complexity of your website. Properly configured SSR significantly improves performance and search engine optimization (SEO) by avoiding the client-side rendering delay.

Optimizing MathJax for Performance

Optimizing MathJax for performance is crucial, particularly for websites with numerous complex equations. Techniques for performance optimization include:

By implementing these optimization techniques, you can significantly improve the performance and user experience of websites that extensively use MathJax for rendering mathematical equations.

Advanced Topics

Configuration Options

MathJax offers extensive configuration options to customize its behavior and appearance. These options are specified using a JavaScript object passed to the MathJax global object before loading the MathJax script. The configuration object allows control over various aspects of MathJax, including:

The configuration object’s structure can be quite complex. Refer to the MathJax documentation for a complete list of configuration options and their usage. Example snippet:

MathJax = {
  tex: {
    inlineMath: [['$', '$'], ['\\(', '\\)']],
    displayMath: [['$$', '$$'], ['\\[', '\\]']],
    processEscapes: true,
    tags: 'ams',
    macros: {
      "\\R": "\\mathbb{R}"
    }
  },
  svg: {
    fontCache: 'global'
  }
};

Customizing MathJax Behavior

Beyond configuration options, you can customize MathJax behavior through several methods:

Extending MathJax Functionality

Extending MathJax involves creating custom extensions or plugins to add new features or modify existing ones. This typically involves writing JavaScript code that interacts with the MathJax API.

Contributing to MathJax

Contributing to MathJax involves improving the core library, developing new extensions, or enhancing the documentation.

Contributing to MathJax benefits both the project and the broader community by improving its functionality, reliability, and accessibility.

Appendix: MathJax Cheat Sheet

Common Symbols and Commands

This cheat sheet provides a quick reference for commonly used symbols and commands in MathJax using LaTeX syntax. Remember to enclose inline formulas in $...$ and display formulas in $$...$$.

Greek Letters:

Letter Command Letter Command
α \alpha Α \Alpha
β \beta Β \Beta
γ \gamma Γ \Gamma
δ \delta Δ \Delta
ε \epsilon Ε \Epsilon
ζ \zeta Ζ \Zeta
η \eta Η \Eta
θ \theta Θ \Theta
ι \iota Ι \Iota
κ \kappa Κ \Kappa
λ \lambda Λ \Lambda
μ \mu Μ \Mu
ν \nu Ν \Nu
ξ \xi Ξ \Xi
ο \o Ο \Omicron
π \pi Π \Pi
ρ \rho Ρ \Rho
σ \sigma Σ \Sigma
τ \tau Τ \Tau
υ \upsilon Υ \Upsilon
φ \phi Φ \Phi
χ \chi Χ \Chi
ψ \psi Ψ \Psi
ω \omega Ω \Omega

Mathematical Symbols:

Symbol Command Symbol Command
+ + -
× \times ÷ \div
= = \ne
\approx \le
\ge < <
> > \infty
\int \sum
\partial \sqrt{}
π \pi \nabla

Superscripts and Subscripts:

Fractions:

\frac{numerator}{denominator}\(\frac{1}{2}\)

Other Common Commands:

This is not an exhaustive list, but it covers many frequently used symbols and commands. Refer to the full MathJax documentation for a comprehensive reference.

Quick Reference Guide

This guide summarizes essential aspects of using MathJax:

1. Inclusion: Include the MathJax script in your HTML <head>:

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

2. Inline Mode: Enclose inline formulas in $...$: $E=mc^2$\(E=mc^2\)

3. Display Mode: Enclose display formulas in $$...$$:

$$ \int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2} $$

\[ \int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2} \]

4. Essential LaTeX Commands:

5. Troubleshooting: Check your browser’s developer console for JavaScript errors. Verify that MathJax is correctly included and that your LaTeX code is syntactically correct.

6. Further Information: Consult the comprehensive MathJax documentation for detailed information on configuration, extensions, and advanced usage.

This quick reference guide provides a starting point for using MathJax. Explore the full documentation for more advanced features and capabilities.