I've build a form to write LaTeX expressions and render them with MathJax. In order to accelerate the copy of the MathML code, I've writed a script that displays the MathML code in another textarea, as you can see here.
This is my code:
<!doctype html>
<html>
<head>
<title>LaTeX para Word</title>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
showProcessingMessages: false,
tex2jax: {
inlineMath: [
['$','$'],
[ '\\(', '\\)' ]
]
},
extensions: ['toMathML.js']
});
var math = null;
MathJax.Hub.queue.Push(function () {
math = MathJax.Hub.getAllJax('MathOutput') [0];
});
window.UpdateMath = function (TeX) {
MathJax.Hub.queue.Push(['Text', math, '\\displaystyle{' + TeX + '}']);
document.getElementById('output').value = '<?xml version="1.0"?>' + math.root.toMathML("");
};
function selectTextarea(element) {
var text = document.getElementById(element).select();
}
</script>
<script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&locale=pt-br"></script>
</head>
<body>
<textarea id="MathInput" cols="60" rows="10" onkeyup="UpdateMath(this.value)"></textarea>
<div id="MathOutput">
$${}$$
</div>
<hr>
<br>
<textarea id="output" cols="60" rows="10" readonly="readonly"></textarea>
<br>
<button onclick="selectTextarea('output')">Selecionar código</button>
<script src="main.js"></script>
</body>
</html>
The problem is when I type the formula faster, the last character is not displayed on the MathML code. Sometimes, I have to add a space to the end of the formula in order to get the correct MathML code. Anyone can give me some hints to fix this issue?
The problem is that you're mixing asynchronous
calls with synchronous
ones. The Queue
works asynchronously
, so when you're calling this:
MathJax.Hub.queue.Push(['Text', math, '\\displaystyle{' + TeX + '}']);
It doesn't wait for the actual rendering to be completed to go to next line. So this call gets executed before it's completed:
document.getElementById('output').value = '<?xml version="1.0"?>' + math.root.toMathML("");
One way to solve it would be to queue the output update as well, which you can do by creating another function that takes care of the output and queueing it after the render, so it'll be executed only when rendering is complete. Like this for example:
window.updateMathMl = function (math) {
document.getElementById('output').value = '<?xml version="1.0"?>' + math.root.toMathML("");
};
window.UpdateMath = function (TeX) {
MathJax.Hub.queue.Push(['Text', math, '\\displaystyle{' + TeX + '}'], [updateMathMl, math]);
};