Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Markdown with MathJax like Math StackExchange

UPDATED POST

Ok I've managed to make Markdown and MathJax work together, it was relatively simple actually. I've used marked together with MathJax.

$(function() {
    var $text       = $("#text"), // the markdown textarea
        $preview    = $("#preview"); // the preview div

    $text.on("keyup", function() {
        $preview.html( marked($text.val()) ); // parse markdown
        MathJax.Hub.Queue(["Typeset", MathJax.Hub, "preview"]); // then let MathJax do its job
    })
});

Problem now is: I think markdown is parsing my math 1st before MathJax can change it. How do i fix this? I think its fixed on Math StackOverflow, but how? I need to stop markdown from parsing math

UPDATE 2

This works, but not sure if its the way math.stackexchange does it, but it seems to produce similar/same results with what I tested so far ...

$(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( marked($preview.html()) );
    });
});

OLD POST BELOW

In the math stackexchange, I can use MathJax with Markdown. I wonder what do I need to do that? I can use a library like marked to render Markdown, but for MathJax, it seems like it just renders on page loads. How can I call it to re-render or better just render whats needed (specified by me)

html = marked("some markdown string") // a HTML string
// is there something like
html = MathJax.parse(html)

UPDATE

I think I should be looking at http://www.mathjax.org/docs/1.1/typeset.html#manipulating-individual-math-elements. But when I try

$text.on("keyup", function() {
    $preview.html( marked($text.val()) );
    var math = MathJax.Hub.getAllJax("preview");
    console.log(math);
    MathJax.Hub.Queue(["Text", math, "a+b"]);
})

Where:

  • $text: is the jQuery element for my textarea
  • $preview: is the preview div

I find that math is undefined, so it seems var math = MathJax.Hub.getAllJax("preview") is not working. I have a div#preview btw.

like image 833
Jiew Meng Avatar asked Aug 22 '12 09:08

Jiew Meng


1 Answers

The fastest way is to protect the math from your markdown-parser.

See this question for a detailed answer by Davide Cervone, including a link to the code used by math.SE.

like image 193
Peter Krautzberger Avatar answered Nov 01 '22 15:11

Peter Krautzberger