Conditional formatting (with JavaScript) doesn't work anymore

I have a note type that shows a quote that you have to judge is true or false.
Based on the answer, the quote is highlighted in green or pink (light red).

The back template looks like this:

<div class="quote">"{{quote}}"<br></div>

let quoteanswer = document.querySelector(".quote");
switch("{{true or false}}") {
case 'true': = "lightgreen";
case 'false': = "pink";

This note type used to work perfectly, but recently a bug has appeared.
The first time in a given study session a note of this type appears, it still works correctly, however all subsequent times the quote is no longer highlighted in the respective color.

Somehow the script is only executed correctly once.

What could be the cause of this?

1 Like

Try replacing let with var.


That worked! Why did it work? :face_with_monocle:

The <script> will be executed every time, you go to the next card, but in the same context.

If you use a let assignment with the same identifier (quoteanswer in this case) multiple times, JavaScript will complain, that "quoteanswer has already been defined".
However, with var, you’re allowed to redefine the variable.

TLDR, because this is valid JS:

var a = 5;
var a = 10; // OK: a is now 10

but this is not:

let a = 5;
let a = 10; // ERROR:  a has already been defined

Understood. Thanks for the clarification!
Is it possible that a recent Anki update has made it so that cards are now rendered in the same context?

Yes, it’s like that since version 2.1.41. Before, these script tags didn’t persist between cards. AnkiDroid still handles this the “old” way and refreshes every time, but that’s not very efficient and they’ll likely follow Anki Desktop’s example some day in that regard.