Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting MathJax into ContentEditable div

I am trying to insert some MathJax code into a contentEditable div, like so:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
  <script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML">      </script>

</head>
<body>
  <div id="editor" contentEditable="true" style="width:400px;height:400px;">
 </div>

and the JS

$(document).ready(function () {

  $('#editor').focus();

  var code = "\\alpha";

  var html = '<span id="_math"><script type="math/tex;mode=in-line">'+ code +'</script></span>';

  document.execCommand('insertHTML', false, html);

  MathJax.Hub.Queue(["Typeset", MathJax.Hub, '_math']);

});

Which renders OK, but once this is inserted, the element freezes and further input is not possible. Can someone point out the problem here.

like image 524
user997712 Avatar asked Nov 12 '22 20:11

user997712


1 Answers

You need to call MathJax when the content changes. See this fiddle: http://jsfiddle.net/rfq8po3a/ (note, I had to escape the < and > in html).

This was achieved with a few things:

1) move the MathJax logic into its own function, refreshMathJax which will re-populate the tag and code.

2) call this function when first loading the page, and again onBlur.

3) Clear the editable element onFocus. Without this, the editable element can't be reused easily. You can change the onFocus callback function to instead replace the contentEditable html with the original LaTeX content.

like image 53
goldins Avatar answered Dec 09 '22 12:12

goldins