Search code examples
javascriptmathjax

Equations are not being formatted when I append new equation MathJax


I am facing a problem using mathjax. the equations already available are formatted but the equations that I put by myself are not being formatted.

here is my code:

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script async="true" src="https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js?config=AM_CHTML">
    </script>
</head>

<body>
    <input type="text" id="eq">
    <button onclick="amb()">equation</button>
    <p id="amb"></p>
    <p>`x^3`</p>
    <script>
        function amb() {
            eq = document.getElementById('eq').value;
            document.getElementById('amb').append("`" + eq + "`");
        }
    </script>
</body>

</html>


Solution

  • First, I suggest use a form and a type=submit button for a better UX. I found the solution you need to queue an action to rescan the page: MathJax.Hub.Queue(["Typeset",MathJax.Hub]);

    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    
      <script async="true" src="https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js?config=AM_CHTML">
      </script>
    </head>
    
    <body>
      <form onsubmit="amb(); return false">
        <input type="text" id="eq">
        <input type="submit"  value="equation">
      </form>
      <p id="amb"></p>
      <p>`x^3`</p>
      <script>
        function amb() {
          eq = document.getElementById('eq').value;
          document.getElementById('amb').innerText = ("`" + eq + "`");
          MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
          
        }
    
      </script>
    </body>
    
    </html>