Search code examples
mathjax

Execute MathJax for custom tags without delimiters


I want to use mathjax on our page and i have a custom tag with the formulas <formula>.

However it works only when i use delimiters inside my custom tag, is it possible to get rich of the delimiter?

When i set inlineMath: [['', '']] the whole thing hangs up.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>title</title>
    <link rel="stylesheet" href="style.css">
	<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
	<script>
	  MathJax = {
		tex: {inlineMath: [['$', '$']]},
		startup: {
		  elements: ['formula'],
		  ready: function () {
			MathJax.startup.defaultReady();
		  }
		}
	  }
	</script>
    <script id="MathJax-script" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
  </head>
  <body>
    <p>hello world</p>
	<p>this is a <formula>x^2 + y^2 = z^2</formula> formula x^2 + y^2 = z^2</p>
	<p>this is a <formula>$x^2 + y^2 = z^2$</formula> formula x^2 + y^2 = z^2</p>
  </body>
</html>


Solution

  • You can do something similar to the example given in the documentation that shows how to process the old v2-style <script> tags that used to be used to hold the math.

    Here is an example:

    <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
    <script> 
    MathJax = {
      options: {
        renderActions: {
          find: [10, function (doc) {
            for (const node of document.querySelectorAll('formula')) {
              const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], false);
              const text = document.createTextNode('');
              node.parentNode.replaceChild(text, node);
              math.start = {node: text, delim: '', n: 0};
              math.end = {node: text, delim: '', n: 0};
              doc.math.push(math);
            }
          }, '']
        }
      }
    };
    </script> 
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    
    <p>this is a <formula>x^2 + y^2 = z^2</formula> formula x^2 + y^2 = z^2</p>

    Note that this replaces the usual math-finding function with this one that looks for <formula> tags, so if you want to use the original delimiters as well, change the find: [10 to findTags: [9 so that the original will not be replaced and will run after your code runs.

    Note also that this does not give you a means of distinguishing display-style math from in-line math (as the TeX delimiters do), so all the math is in in-line style. You could, of course, modify the code to have two different tags, or allow an attribute on <formula> to specify display style.