Skip to content

Instantly share code, notes, and snippets.

@pkra
Created August 1, 2016 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkra/bedb22fa19aa1a5495ae31f605caa35f to your computer and use it in GitHub Desktop.
Save pkra/bedb22fa19aa1a5495ae31f605caa35f to your computer and use it in GitHub Desktop.
Use TeX in alt-text of images for rendering with MathJax
(function () {
var images = document.getElementsByTagName('img');
var hasMath = false;
for (var i = 0; i < images.length; i++){
var image = images[i];
tex = image.getAttribute('alt');
if (tex && tex[0] === '$'){ // TODO a class for TeX images would be cleaner, also to differentiate inline and display math
hasMath = true;
var preview = document.createElement('span');
preview.setAttribute('class','MathJax_Preview');
image.parentNode.insertBefore(preview, image);
preview.appendChild(image);
var script = document.createElement('script');
script.type = 'math/tex';
script.text= tex.substring(1,tex.length-1); // strip dollars from TeX string
preview.parentNode.insertBefore(script, preview.nextSibling)
}
}
if (hasMath){ //if there's math, load MathJax
var mathjax = document.createElement('script');
mathjax.src= 'https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML-full';
document.head.appendChild(mathjax);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment