Issue with shortcut for a button

I think I know what the bug is here.

On Anki desktop, due to how global variables are maintained from card front to back and between reviews, the keyup eventListener is actually stored between reviews. So, each time a card back is rendered, another eventListener is added, meaning that pressing the shortcut key actually presses the button multiple times depending on how many cards you’ve reviewed so far.

The code in myFunction where it does this

if(el.style.display ==="block") {
 el2.style.display = "block";
el.style.display = "none";
} else {
 el2.style.display = "none";
el.style.display = "block";
}
}

is an effect that reverts to the previous state, if it were run again. So, clicking the button twice in a row would appear to do nothing. Thus, when the the number of times the shortcut clicks the button is odd, it works, when it’s even it doesn’t. This creates the alternating effect as the number of clicks goes up by 1 each time you render a card back.

This can be fixed by changing the code to be like this

  // Custom shortcut for button
  // Prevent adding the same shortcut multiple times on Anki Desktop
  // The listenerAlreadyAdded variable will be undefined on the first card review which will
  // cause the addKeyupListener function to be called
  // On subsequent card reviews, the listenerAlreadyAdded variable will already be true
  // and the addKeyupListener function will not be called again
  // On AnkiDroid, the listenerAlreadyAdded variable will always be undefined and eventListeners
  // will be added on every card review as they aren't persistent
  var listenerAlreadyAdded = !!listenerAlreadyAdded;
  function addKeyupListener() {
    listenerAlreadyAdded = true;
    document.addEventListener("keyup", function (event) {
      if (event.key == "`") {
        myFunction();
      }
    });
  }
  if (!listenerAlreadyAdded) addKeyupListener();

As a sidenote, instead of getting the button element and clicking, you can just call myFunction in the eventListener function. The current code would immediately break if you ever added a second button somewhere as it’s simply fetching any button it finds.


Thanks to your bug, I realized I was actually making the same error in one of my cards. I never realized because in my card running the function multiple times did nothing noticeable, except very occasionally I’d notice some lag when using the shortcut during long review sessions on desktop. Which was probably caused by the function being called a hundred times on the key press :laughing:

5 Likes