JavaScript blocks display of the other side of card

I’m designing a card type using JavaScript.
I want a card to show only a part of a field content.
For instance, if Eng field contains
spine<br>backbone
I want the front of the card to display
spine
(the part before new line).

Front template looks like this:

<script>
let list = "{{Eng}}".replace("<br>", "\n");
let word = list.match(/.*/);
document.write("Eng: ");
document.write(word);
document.write("<br>Rus?");
</script>

Back template looks like this:

{{Rus}}

When I review this card, the front side is displayed correctly:
Eng: spine
Rus?

But when I click Show answer, the back side, instead of showing {{Rus}}
позвоночник
shows the same what was displayed on the front side:
Eng: spine
Rus?

If I delete JavaScript from the front template and write only {{Eng}}, then both the front and back sides are displayed correctly. But if I add JavaScript on the front side, the other side of the card stops working.

I saw some ideas about using .innerHTML instead of document.write and also about adding {} around the code, but I don’t understand their application and therefore cannot test them.

Is the issue with my code or with Anki? How to fix it?
PS: I’m using latest version of Desktop Anki (2.1.49) on Windows 10.

Just as an aside, this has nothing to do with your topic, but for the ease of read of people you will answer you question: this forum uses Markdown.
This means that to write HTML code, you can enclose it in triple backquotes:

```html
<script>
let list = "{{Eng"".replace("<br>", "\n");
...
</script>
```

will render as

<script>
let list = "{{Eng}}".replace("<br>", "\n");
...
</script>
1 Like

Thank you, BlackBeans! I applied it and the post looks better now

The problem here is mainly document.write(), which clears the document on first write as far as I understand from Document.write() - Web APIs | MDN

Try this front template:

<div id="front"></div>

<script>
var list = "{{Eng}}".replace("<br>", "\n");
var word = list.match(/.*/);
var front = document.getElementById("front");
front.innerHTML = `Eng: ${word}<br>Rus?`;
</script>

You also have to use var instead of let or you will get errors because Anki uses the same webview for front and back templates and only recycles it periodically.

3 Likes