(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.
-
Desktop
Introduction - Writing Anki Add-ons
- You can now debug the webviews using an external Chrome instance, by setting the env var QTWEBENGINE_REMOTE_DEBUGGING to 8080 prior to starting Anki, then surfing to localhost:8080 in Chrome.
-
AnkiDroid
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
orwindow.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
orconst
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...
orquerySelector(All)
. In such cases, wrapping the process with thesetTimeOut()
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>