# How to enable mathjax rendering in live preview ?

2.5k views
in Plugins

I want to to enable  MathJax rendering in live preview of Markdown editor . I found following snippet on stackoverflow :

$(function() { var$text       = $("#text"),$preview    = $("#preview");$text.on("keyup", function() {
$preview.html($text.val() );
MathJax.Hub.Queue(["Typeset", MathJax.Hub, "preview"]);
});

MathJax.Hub.Register.MessageHook("End Process", function (message) {
$preview.html( q2a-markdown-editor($preview.html()) );
});
});

but it doesn't work .

Can I use this snippet for markdown editor and what should I change ?

Q2A version: 1.5.4

by
edited by

I managed to do it a different way. Goto Markdown.Editor.js and look after an input event function, let's say  the following function

// keyCode 89: y
// keyCode 90: z
if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
event.preventDefault();
}
});
and then modify it to get your mathjax updated as follows:

// keyCode 89: y
// keyCode 90: z
if ((event.ctrlKey || event.metaKey) && (event.keyCode == 89 || event.keyCode == 90)) {
event.preventDefault();
}
var previewID=this.id.replace("input","preview");
window.setTimeout(function(){MathJax.Hub.Queue(["Typeset", MathJax.Hub, previewID]);},10);
});

The purpose of the setTimeout is confirm MathJax run after the keypress event is passed. I sat it to 10 ms, but you may change it to match your needs.

This way is not as efficient as that of stack exchange but works well.

by
It doesn't work for me. Could you test it again?
+1 vote
by

Another simpler way is to run the function on keyup event by adding the following new function into Markdown.Editor.js:

var previewID=this.id.replace("input","preview");
MathJax.Hub.Queue(["Typeset", MathJax.Hub, previewID]);
});

by
Check out this live preview: http://jsfiddle.net/Zky72/2/
by
edited by
Thank you for your answer. I'm so new to programming. Please show me how to configure Markdown.Editor.js . I'm really appreciate it.
+1 vote

For me, the best way to address this is for the Markdown Editor to ask MathJax to refresh the typeset each time the Markdown Editor refreshes the preview.  To do this, insert the following line into Markdown.Editor.js:

MathJax.Hub.Queue(["Typeset", MathJax.Hub, panels.preview.id]);

Put this line at the very end of the function makePreviewHtml.  Next, to enable this, modify qa-markdown-editor.php so that it uses the non-minified version of the JavaScript files.  And of course, add MathJax to your Q2A site.

The reason why I like this approach is that it updates MathJax at the same moment that it updates the Markdown preview, so there is no flashing effect in the browser.

by
unfortunately, it seems not work.