Anki Forums

Javascript bug. The card appears empty on anki desktop

Follow this post I trying to simulate the behavior of cloze. Get a phrase with words in double brackets to be hidden on the front and shown in bold on the back. My front template is:

{{Sentence1}}

  <script>
    var cloze = document.body.innerHTML.match(/\[\[(.*?)\]\]/gi)
    for (var i = 0; i < cloze.length; i++) {
	document.body.innerHTML = document.body.innerHTML.replace(cloze[i], cloze[i].replace(/^\[\[(.*)\]\]$/g, "<span class=\"cloze\">$1</span>"))
    }
  </script>

and in back

.card {
  font-family: arial;
  font-size: 20px;
  text-align: center;
  color: black;
  background-color: white;
}

.cloze {
  font-weight: bold;
}

my Sentence1 field has this is an [[example]] sentence.

The card appears completely empty in anki, but in chrome’s ankitab extension it looks fine.

Attached screenshots. In ankidroid it works fine, but not in anki.

Maybe this should not be called a bug, it’s just that the script in that post is not compatible with version 2.1. If you want to use it, you just need to modify it to work.

Anki desktop(ver2.1) updates only part of the document, not the entire document.body, when displaying a card, and probably because of this, updating the entire document with innerHTML property may not work as expected. There are some possible solutions to this, but a relatively easy one is to limit the part you get and replace with innerHTML property to the inside of the range that is updated when each card is displayed.

Here is an example of a template that also works on Anki Desktop 2.1:

Front Template:

{{Front}}
<script id="my-script">
    var regex = /\[\[(.*?)\]\]/gi;
    var repl = `<span class="cloze">$1</span>`;
    var container = document.querySelector('#my-script').parentElement;
    container.innerHTML = container.innerHTML.replace(regex, repl);
</script>

Styling:

.cloze {
    color: orange;
}

Screenshot:

See also here:

3 Likes