After using Anki for arithmetic tables for a while, it’s become evident that it would be beneficial to teach my kids to recognize different expressions of the sum and difference. Specifically, there are four distinct forms: x + y, add x to y, x increase by y, sum of x and y. Why wouldn’t we employ JavaScript in the card templates to pick a random wording as the question?

The code turned out to be trivial indeed. We just need to prepare a place holder for the question, capture the field values into JS variables, pick a random phrase from an array, and inject it into the placeholder.

<small class="deck">{{Deck}}</small><br/><br/>

<span id="ask"></span>
<script>
var x = "{{a}}";
var y = "{{b}}";
var questions = [`до ${x} додати ${y}`, `${x} збільшити на ${y}`, `${x} + ${y}`, `сума чисел ${x} і ${y}`];
document.getElementById("ask").innerHTML = questions[Math.floor(Math.random() * questions.length)];
</script>

{{type:c}}

There are a couple of caveats:

  • The code will have to be repeated in every card template because Anki doesn’t allow to include chunks of JavaScript code from external files. It’s possible to work around the limitation, but it wouldn’t work with AnkiDroid, for instance.

  • The script will execute every time the card is rendered, for example, when the card is flipped to the back side that contains {{FrontSide}}. Thus, the back side will likely display a different question than the front side.

Anki JS illustration