MathJax - set cursor position
We aim to have a text box where we can enter math, and when we click on an element in the resulting math output, the cursor moves to that place in the text box.
This works for all digits, variables, symbols and even parentheses in this demo, but will not necessarily work for other symbols or more complex expressions (see below).
Instructions
You can edit the math in the text area (yellow background). When you click on a number or variable in the math output (green background), the cursor will move to that portion of the LaTeX in the text box.
Technique summary
- Before loading MathJax, we set
startup: {typeset: false}
so that it doesn't start processing immediately. On load, we instruct MathJax to process the math and then we can add our event listener to all the math elements (numbers and variables). - Find the index of the sub-element containing the math that we clicked on
- Get the "content" value of the pseudo-element ":before" (this is "x" or "2" or whatever)
- Find the index of that letter or number or function in the textarea
- Move the cursor to that value (letter or number or function) in the text box.
NOTE: This finds things like \sqrt
and \int
and functions like sin
. Everything works in the demo, but no guarantees when more complex things are involved. It's not very happy when environments are involved.
Also, there needs to be a lookup table for many of the possible symbols beyond the Greek letters already catered for.
I'll leave the solution of any further issues as an exercise for the reader :-).