Search code examples
javascripthtmllatexmathjax

Using latex to color variables in javascript


I have the following line in my javascript running, which will format a cubic equation in latex/mathjax to display, while including variables from the code:

document.getElementById("demo").innerHTML = "$y = $" + xzero + "$ + $" + xone + "$x + $" + xtwo + "$x^2 + $" + xthree + "$x^3$";

What I want to do now is color the part of the equation where the variable is. I thought something like

...= "$y = \color{#AF0}{$" + roundNum(xzero) + "$} + $"...

would work, but it seems evident that it does not. Could I get some help on how I could color the variables in my equation?


Solution

  • Did you do this after your line of code that sets innerHTML of #demo?

    MathJax.Callback.Queue(["Typeset", MathJax.Hub, "demo"]);
    

    At me,

    "$y = \\color{#AF0}{" + roundNum(xzero) + "} + "... +"$";
    

    worked, and remove dollar signs in the midle of the equation, put them only at the start and the end (like I did).

    This is how it should look like:

    document.getElementById("demo").innerHTML = "$y = \\color{#AF0}{" + roundNum(xzero) + "} + "... +"$";
    MathJax.Callback.Queue(["Typeset", MathJax.Hub, "demo"]);
    

    EDIT:

    I doubled the backslashes like @Davide Cervone said.