Javascript: convert <textarea> with markdown + latex formatting to html

170 Views Asked by At

Essentially I'm trying to create an input area that allows the user to enter markdown as well as latex (using $..$ and $$..$$), very similar to what you can do in an R notebook. As the user enters text, I'd like to convert it into a html format (and display it in another div).

I was able to get the markdown working well with showdown from reading other questions as shown below

<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script>

document.getElementById('markdown-input').addEventListener('change',function(){
    var markdownConverter = new showdown.Converter();
    markdownText = document.getElementById('markdown-input').value;

    var html = markdownConverter.makeHtml(markdownText);
    document.getElementById('markdown-container').innerHTML = html;
});

The trouble I am having is how to get the Latex working. I have been reading up on Mathjax, but have been having a lot of trouble trying to figure out how to get that working alongside this especially with version 3. I have currently got the following scripts to use Mathjax, but unsure how to get these to work with the code above.

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({tex2jax: { inlineMath: [ ["$", "$"], ["\\(","\\)"] ], displayMath: [ ["$$","$$"], ["\\[", "\\]"] ]}});
  </script>
  <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>

Any advice on how to get this working would be really appreciated.

1

There are 1 best solutions below

0
On

After a few more hours of research, I've managed to get it working.

I found my way to Configuring MathJax, to modify my existing reference to the MathJax js files:

<script>
MathJax = {
  tex: {inlineMath: [['$', '$'], ['\\(', '\\)']]}
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>

Then it was a simple code from another section of the documentation Dynamic Content, which calculates all the latex within the page synchronously, which I typed after parsing the markdown: MathJax.typeset();

I'm not sure if there is a way to optimise this to only run for a particular element and its children, but it is currently working exactly how I need it to.