Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating fractions dynamically with Javascript inside content-editable div

What I'm developing is a web page that allows the user to enter math equations and phrases into a visual space, without the use of an actual keyboard. So far what I have is the visual space, which is a contenteditable div tag, as well as an area underneath with input buttons for placing numbers and mathematical symbols into said div. Now what I need is some way of allowing the user to enter fractions into the div. I thought of maybe somehow using Javascript to go into and out of subscript/superscript "mode" and stacking numbers on top of each other separated by a line, and then have a button signifying that the user has finished entering numbers into the fraction, but my knowledge of JS is very limited at this point. How would I go about doing this?

like image 738
Ben Avatar asked Jul 01 '26 14:07

Ben


1 Answers

You have parsing problem here. I used regex to match a predefined pattern I chose laTex style {DIGIT}|{DIGIT}

 function transformFracs() {
 //Grab digits with in {} recording only the numbers
 var regex = /{(\d+)}\|{(\d+)}/;
 //Cache for performance!
 var div = $(this);
 //Replace using html fraction notaion
 var afterReplace = div.html().replace(regex,
     "<sup>$1</sup>" +
     "&frasl;" +
     "<sub>$2</sub>")
 //Replace content of original div
 div.html(afterReplace);
 }
$(".editable").blur(transformFracs);

Check out the fiddle to play around with it.

like image 124
raam86 Avatar answered Jul 04 '26 02:07

raam86



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!