Reputation: 141
I used MathJax for displaying mathematics equations.It is working fine in statically written mathematics. But not working for dynamically added mathematics.
Here is my code
<body>
//Static
<div>
<span>\(x = {-b \pm \sqrt{b^2-4ac} \over 2a}\)</span>
</div>
//Dynamic
<div id="dynamic-pan">
</div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#dynamic-pan').empty();
$('#dynamic-pan').append('<span>\(x = {-b \pm \sqrt{b^2-4ac} \over 2a}\)</span>');
});
</script>
</body>
I have written mathematics in two span element. First one is statically declared and second one is dynamically added in document ready function
Please help me to resolve the issue.
Upvotes: 4
Views: 7450
Reputation: 4876
http://docs.mathjax.org/en/latest/web/typeset.html
MathJax.typeset()
MathJax.typesetPromise()
setTimeout(function () {
const content = document.createElement('span')
content.textContent = '\\(x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}\\)'
const done = document.createElement('span')
done.textContent = ' done!'
const syncTypeset = document.querySelector('#syncTypeset')
syncTypeset.appendChild(content.cloneNode(true))
setTimeout(function () {
MathJax.typeset()
syncTypeset.appendChild(done.cloneNode(true))
}, 3000)
const asyncTypeset = document.querySelector('#asyncTypeset')
asyncTypeset.appendChild(content.cloneNode(true))
setTimeout(async function () {
await MathJax.typesetPromise()
asyncTypeset.appendChild(done.cloneNode(true))
}, 3000)
}, 0)
<script>
MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']]
},
svg: {
fontCache: 'global'
}
};
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" id="MathJax-script"></script>
//Static
<div>
<span>\(x = {-b \pm \sqrt{b^2-4ac} \over 2a}\)</span>
</div>
//Dynamic
<div id="syncTypeset">Sync after 3 second: </div>
<div id="asyncTypeset">Async after 3 seconds: </div>
You need to tell MathJax to look for unprocessed math which is done with the Typeset()
method, since MathJax may be operating at the time of the call to Typeset()
you need to add it to its queue
$(document).ready(function() {
var $el = $('#dynamic-pan')
$el.empty()
$el.append('<span>\\(x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}\\)</span>')
MathJax.Hub.Queue(['Typeset', MathJax.Hub, $el[0]]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML"></script>
//Static
<div>
<span>\(x = {-b \pm \sqrt{b^2-4ac} \over 2a}\)</span>
</div>
//Dynamic
<div id="dynamic-pan"></div>
Refer to this document for more information
Edit: the character \
has a special meaning on strings (it escapes the following char) to avoid this behavior make sure you use \\
for it to appear in the final string
Upvotes: 9