javascriptanki

conditional formatting of anki deck class style with javascript based on a hidden variable


I have a basic anki deck configuration, I'd like to add colors for gender of a noun word in latin languages (Portuguese, to be specific):

Front: man

Back: homem

Example:

Gender: m

enter image description here

<-- for contrast, I'll write example of another card --> Front: woman

Back: mulher

Example:

Gender: f

enter image description here

For better memorization, I force to type my answers:

{{Front}}
<br>
{{type:Back}}

so far so good.

Now, I created my styling:

.card-m {
 font-family: Arial;
 font-size: 26px;
 text-align: center;
 color: white;
 background-color: #66d;
}

.card-f {
 font-family: Arial;
 font-size: 26px;
 text-align: center;
 color: white;
 background-color: #f5426f;
}

.card {
 font-family: Arial;
 font-size: 26px;
 text-align: center;
}

and my back Template card has the following format:

<div id=wrapper class=card-m>
{{FrontSide}}

<hr id=answer>

{{hint:Example}}
</div>

Here's my question: I would like to have a javascript to read the value of Gender variable, and apply class= highlight the back of the card in either Blue, or Pink (for feminine or masculine respectively):

<script>
var x = {{Gender}}.string;
if {{Gender}} == "m"
{ 
  document.getElementById("wrapper").class='card-m';
}
else
{ 
  document.getElementById("wrapper").class='card-f';
}
</script>

But the Gender variable seems to have no effect on the class that is being applied.

Any idea why?


Solution

  • It looks like some of the HTML and JS syntax was not correct. Also, the {{Gender}} card field can be directly inserted into a string.

    I was able to make it work with these changes to your code.

    Full Back Template:

    <div id="wrapper" class="">
        {{FrontSide}}
    
        <hr id="answer">
    
        {{hint:Example}}
    </div>
    
    <script>
    
    var x = "{{Gender}}";
    if (x === "m")
    { 
      document.getElementById("wrapper").className = "card-m";
    }
    else
    { 
      document.getElementById("wrapper").className = "card-f";
    }
    </script>