Search code examples
javascripthtmlmathjax

Displaying MathJax in innerHTML attribute calling from a function


Consider the code I have:

<!DOCTYPE html>
<html>
<body>

<h1>The select element</h1>
<p id="text"></p>

</body>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
    document.getElementById("text").innerHTML="$$hello$$";
</script>
</html>

It woks fine and shows the text hello in MathJax format in text id paragraph. But, if I introduce here a function, say:

<!DOCTYPE html>
<html>
<body>

<h1>The select element</h1>
<button onclick="start()">Click</button>
<p id="text"></p>

</body>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
function start(){
    document.getElementById("text").innerHTML="$$hello$$";}
</script>
</html>

Clicking the button that has click written on it, only shows the text $$hello$$ in the text tag. Now, how do I change it? Actually, why do such thing happen?


Solution

  • Mathjax doesnot handle DOM changes, since you are inserting HTML content on click event, you need to inform MathJax that DOM has changed so that it can look into the DOM and render the mathematical content, you need to call Mathjax's typeset() function to do that, like:

    ..
    function start(){
        document.getElementById("text").innerHTML="$$hello$$";
        // call the typeset
        MathJax.typeset();
    }
    ..
    

    typeset() runs synchronously lookin for any unprocessed math content in the DOM and typesets that content.