Interacting with a mathfield

Reading the content of a mathfield

The content of a mathfield is available with the value property, just like with a <textarea>.

To be notified as soon as the content of the mathfield is modified listen for an 'input' event.

Try: modify the 'input' event to a 'change' event. Notice how this event is only sent if you press the Return or Enter key, or when the mathfield loses focus and the content has been modified

document.getElementById('formula').addEventListener('input',(ev) => { // `` is an instance of `MathfieldElement` console.log(; });
<script src="//"></script> <math-field id="formula"> x=\frac{-b\pm \sqrt{b^2-4ac}}{2a} </math-field>

The value property is equivalent to calling the getValue() method with no argument. You can control how the result is formatted by passing options to getValue(). For example to get the content as an ASCIIMath string, use getValue('ascii-math).

Try: Other formats are available: change 'ascii-math' to 'spoken-text'.

document.getElementById('formula').addEventListener('input',(ev) => { // `` is an instance of `MathfieldElement` console.log('ascii-math')); });
<script src="//"></script> <math-field id="formula"> x=\frac{-b\pm \sqrt{b^2-4ac}}{2a} </math-field>

Changing the content of a mathfield

You can change the value of the mathfield programatically. In the example below, the Latex input field is editable and is reflected in the mathfield (and vice-versa).

Note that we use the suppressChangeNotifications option when changing the content of the mathfield, to prevent a 'input' event from being triggered and creating an infinite loop.

import MathLive from 'mathlive'; const mf = document.getElementById('formula'); mf.addEventListener('input',(ev) => { document.getElementById('latex').value = mf.value; }); // document.getElementById('latex').value = mf.value; // // Listen for changes in the latex text field, and reflect its value in // the mathfield. document.getElementById('latex').addEventListener('input', (ev) => { mf.setValue(, {suppressChangeNotifications: true}); });
<label>Mathfield</label> <math-field id="formula"> x=\frac{-b\pm \sqrt{b^2-4ac}}{2a} </math-field> <label>Latex</label>


Customizing a mathfield
How to customize the behavior and appearance of a mathfield.
Web Component Lifecycle
Understand in depth the lifecycle of a MathfieldElement: construction, interaction with the DOM and when can you communicate with it.