Skip to content

Instantly share code, notes, and snippets.

@Ryan1729
Last active September 21, 2020 16:04
Show Gist options
  • Save Ryan1729/47d5cd3664adae9140bd5a5c19c1e4e6 to your computer and use it in GitHub Desktop.
Save Ryan1729/47d5cd3664adae9140bd5a5c19c1e4e6 to your computer and use it in GitHub Desktop.
Mathjax on textarea keyup
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style type="text/css">body{
margin:40px auto;
max-width:650px;
line-height:1.6;
font-size:18px;
color:#888;
background-color:#111;
padding:0 10px
}
h1,h2,h3{line-height:1.2}
a:link {color: #999;}
a:visited {color: #666;}
</style>
<!-- I think we can assume es6 <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script> -->
<script>
MathJax = {
tex: {inlineMath: [['$', '$'], ['\\(', '\\)']]},
}
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
function typeset() {
let output = document.getElementById('output');
MathJax.startup.promise = MathJax.startup.promise
.then(() => {
MathJax.texReset();
MathJax.typesetClear();
output.innerHTML = document.getElementById("input").value.trim();
return MathJax.typesetPromise()
})
.catch(
function (err) {
//
// If there was an internal error, put the message into the output instead
//
output.innerHTML = '';
output.appendChild(document.createElement('pre')).appendChild(document.createTextNode(err.message));
}
);
return MathJax.startup.promise;
}
</script>
</head>
<body>
<textarea id="input" rows="15" cols="80">
If $a \ne 0$, then $ax^2 + bx + c = 0$ has two solutions,
$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
</textarea>
<br />
<div id="output"></div>
</body>
<script>
function debounce(f, waitTime) {
var timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(f, waitTime);
};
};
document.getElementById("input").addEventListener('keyup', debounce(typeset, 16.6));
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment