Javascript variables' scope and eventlistener guide

I ran into some problems when trying to display a random image from a list, and wanted to share what I found if anyone else needs it, even though javascript is not officially supported.

Variables’ scope

When using let, variables are only in the scope of the current card, however let is not working on AnkiMobile so to create a script for all platforms, var must be used.
The problem with this is that variables are then not reset across different cards.

The solution is to always initialize variables immediately:

var a; // This variable will not be reset on the next cards after being altered
var b = undefined; // This will be reset when a card is loaded
let c; // This will be reset when a card is loaded, but doesn't work on AnkiMobile

Running code on the first card only

Another problem occurring is if you e.g. want to use an eventListener (e.g. for a shortcut) because it will be defined on every card and not deleted again.

This means you have to add code to make it add only on the first card:

const element = document.getElementById('qa'); // An element not changing between cards
if (element.getAttribute('listener') !== 'true') {
	element.setAttribute('listener', 'true');
	// This code is called only for the first card in a study session
	// Add your eventListener here
}
1 Like