## Tuesday, 24 January 2012

### jQuery | Easy TeX Equations

Anyone who has used TEX will agree that no other method of typesetting mathematical equations look nicer. (Thank you Dr. Knuth)

While TEX typesetting can be done easily on your desktop via your favourite program based on the idea, it isn't so on the web.

Of course, there are ways to get this done. You could use the popular jsMath, a JavaScript package which transforms your TEX code into beautiful equations using various fonts and images. You could also use sites such as Code Cogs where you can produce equation images which can then be included into your blog post. These methods however, often require extra processing client-side, and/or more time spent on producing the intended result.

I will talk about a very easy method of doing an equivalent of the above.

Here's the Schrödinger equation for a taster:
i\hbar\frac{\partial\psi}{\partial t} = \frac{\hbar^2}{2m}\nabla^2\psi + V(\mathbf{r})\psi

The method I am about to introduce, uses one of Google's many resources: The Infographics Tool, based on the Chart API.
As mentioned in the API information page, all you need to do to get an equation image, is to get the image from a specific URL where Google does all of the complicated processing.

## The Code

The following script does the job, assuming that you have jQuery installed.
function TeXify () {
$('code.tex').each(function(i, e) { e =$(e);
e.replaceWith('<img class="tex" src="http://'+
+(i % 10)
+encodeURIComponent(e.text())+'"/>');
});
}
\$(document).ready(TeXify);

For example, it converts the following declaration of TEX code:
<code class="tex">e^{i\pi}+1=0</code>

into this, once the page is loaded:
e^{i\pi}+1=0

## Styling

If you want to make your image blend in, simply declare a set of CSS styles as follows:
img.tex {
display: block;
margin: 5px auto;
border: none !important;
background-color: transparent !important;
}

## Conclusion

While this solution has the downside (as all JavaScript solutions do) that it won't work if your user does not have JavaScript enabled, it is definitely one of the fastest solutions available as you do not have to leverage client resources, but Google's, and we all know Google is blazing fast.

Now, it's time to show off your newly prettified math pages!

## Examples

E=mc^2
<code class='tex'>E=mc^2</code>

\Delta x \Delta p \geq h
<code class='tex'>\Delta x \Delta p \geq h</code>

\oint\limits_c \, \mathbf{A}\cdot\mathbf{dl} = \iint\limits_s \, \nabla\times\mathbf{A}\cdot\mathbf{ds}
<code class='tex'>
\oint\limits_c \, \mathbf{A}\cdot\mathbf{dl} = \iint\limits_s \, \nabla\times\mathbf{A}\cdot\mathbf{ds}
</code>