I have two fields which, if possible, would like to know how to randomize their order.
{{Simplified}} and {{Traditional}} respectively contain information which I want to randomly alternate between:
{{Simplified}}
{{Traditional}}
and
{{Traditional}}
{{Simplified}}
So they switch places between them and one appears first. Not changing from front to the back of the card or anything like that, I’m looking for a script which alternates their positions in the back of the card or the front of the card so I don’t remember their positions and they keep switching. Is this possible to do?
Thanks for the help!
Try the following:
<div class="shuffle">{{Field 1}}</div>
<div class="shuffle">{{Field 2}}</div>
<div class="shuffle">{{Field 3}}</div>
<div id="container"></div>
<script>
// https://stackoverflow.com/a/12646864
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
setTimeout(() => {
const fields = [...document.querySelectorAll(".shuffle")];
shuffleArray(fields);
fields.forEach((fld) => document.getElementById("container").appendChild(fld));
}, 0);
</script>
1 Like
Works wonderfully! Is it possible to add a < hr > or < br > tag between the fields? I’ve tried but it didn’t work.
It can be done by replacing this part of the above code:
setTimeout(() => {
const fields = [...document.querySelectorAll(".shuffle")];
shuffleArray(fields);
fields.forEach((fld) => document.getElementById("container").appendChild(fld));
}, 0);
with:
setTimeout(() => {
const fields = [...document.querySelectorAll(".shuffle")];
shuffleArray(fields);
const container = document.getElementById("container");
fields.forEach((fld, index) => {
if (index !== 0) {
container.appendChild(document.createElement("hr"));
}
container.appendChild(fld);
});
}, 0);
2 Likes
Could you, please, explain why do we need to use setTimeout()?
This was posted a year ago, so I can’t remember exactly why I used setTimeout()
, but perhaps it was to ensure that the script would work on AnkiDroid. In my experience, on AnkiDroid, scripts that do not work as expected when run synchronously may work when inserted into the task queue with setTimeout()
.
2 Likes