Search code examples
javascriptjquerymathmathjax

WYSIWYG Editor for Mathematical Equations using MathJax


I am trying to build WYSIWYG Editor to write Mathematical Formulas using MathJax. I am trying to select random content from the textarea and pasting it into a div for converting it into a Mathematical Equations.

<!DOCTYPE html>
<html>
<head>
    <title>Wrap Selected Content with Dummy Editor</title>
    <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>;
    <script type="text/x-mathjax-config">
        MathJax.Hub.Config({tex2jax: { inlineMath: [ ['$','$'], ['\\(','\\)'] ] } });
        MathJax.Hub.Config({tex2jax: { displayMath: [ ['$$','$$'], ['\\(','\\)'] ] } });
    </script>
</head>
<body>
<!--Select some random text from this textarea and click button -->
<textarea id="wrapSelectedContent"></textarea>
<!-- Content should be load here using JavaScript and Convert it into Mathematical Function -->
<div id="pasteSelectedContent" style="width:300px; height:300px; border:2px solid #000;"></div>
<!-- Static Content displayed Successfully -->
<p>$$\sum(a+b)(c+d)$$</p>
<button onclick="wrapContent();">Put Summation Sign</button>
<script type="text/javascript">
    function wrapContent(){
        var selectedContent = document.getElementById("wrapSelectedContent");
        var pasteselectedContent = document.getElementById("pasteSelectedContent");
        var textlength = selectedContent.textLength;
        var start = selectedContent.selectionStart;
        var end = selectedContent.selectionEnd;
        selectedContent.focus();
        selectedContent.setSelectionRange(start,end); 
        var selectedContentValue = selectedContent.value.substring(start, end);
        var replace = "$$\\sum" + selectedContentValue + "$$";
        pasteselectedContent.textContent = selectedContent.value.substring(0,start) + " " + replace + " " + selectedContent.value.substring(end,textlength);        
        console.log("Start Index : " + start);
        console.log("End Index : " + end);
        console.log("Text Content Length : " + textlength);
        console.log(selectedContentValue);
    }
</script>
</body>
</html>

So how can i convert the text displayed in div#pasteSelectedContent with Mathematical Equations Please help me to build this WYSIWYG Editor


Solution

  • Problem Solved

    just insert

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

    after line 32

    pasteselectedContent.textContent = selectedContent.value.substring(0,start) + " " + replace + " " + selectedContent.value.substring(end,textlength);