Search code examples
javascripthtmlstringmathjax

adding math formula string to document using javascript and MathJax


When pressing the button to add the math formula, the MathJax statement does not seem to be interpretet:

const button = document.getElementById('go');
button.addEventListener('click', displayMath, true);

function displayMath() {
    const body = document.body;
    p = document.createElement('p');
    const a = 3, b = 2;
    const c = a + b;
    const math = "\\(" + a + "+ " + b + " = " + c + "\\)";
    p.innerHTML = math;
    body.appendChild(p);
}
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" async
        src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async>
        </script>
    </head>

    <body>
        <p>press the button to display math like this: \(a + b = c\)</p>
        <button id="go" type="button">Go!</button>
        
        <script src="test.js"></script>
    </body>
</html>

1) Can MathJax statements be addet through events like a button click?

2) If not are there better alternatives?

I appreciate any help, thanks :>


Solution

  • You need to run Mathjax parser again, to convert dynamically added expression to math. Here is documentation. So, what you need to do is run MathJax.Hub.Queue(); method on your new expression. Your code should looks like this:

    const button = document.getElementById('go');
    button.addEventListener('click', displayMath, true);
    
    function displayMath() {
        const body = document.body;
        p = document.createElement('p');
        const a = 3, b = 2;
        const c = a + b;
        const math = "\\(" + a + "+ " + b + " = " + c + "\\)";
        p.innerHTML = math;
        body.appendChild(p);
        MathJax.Hub.Queue(["Typeset", MathJax.Hub, p]);
    }
    

    And here is working fiddle