This piece of javascript does not seem to work (hint button)

(Disclaimer: I’m just a user of Anki.)

First of all, Javascript feature in Anki is only intended for advanced users, and is not officially guaranteed to work. See here.

Secondly, you can use Google Chrome to debug the webview of the card screen.

That being said, here are a few things you might want to keep in mind when writing javascript for card templates.

  • You can’t use window.onload or window.addEventListener('DOMContentLoaded', ...), because Anki desktop only updates a part of the DOM tree when displaying a card rather than refreshing the whole page.
  • Do not use let or const at the top level of scripts. This is due to the same reason as above.
  • Loading external scripts with <script src="..."> may not work. In such a case, you need to load them dynamically. See Linking to external javascript for more information.
  • In some cases, you may not be able to properly get the element you want by using getElement(s)By... or querySelector(All). In such cases, wrapping the process with the setTimeOut() function may work.

If I were to rewrite your script, I would probably use a closure and write something like this:

<div id="Hint">Hint</div>
<p id="demo"></p>
<button onclick="revealHintChar();">Hint</button>

<script>
    var revealHintChar = (function () {
        const hintString = document.getElementById("Hint").innerHTML;
        const outputElement = document.getElementById("demo");
        let index = 0;

        return function () {
            outputElement.innerHTML = hintString.charAt(index++ % hintString.length);
        };
    })();
</script>
6 Likes