Randomize font for field?

Is it possible to randomize font color for each word/letter of a field?
I have managed to make it work somewhat but it isn’t consistent. Sometimes it bugs out and throws me black fonts until I close and reopen anki.
Does anyone know of a script or css styling to do this?

1 Like

Here is a quick example of how to give a different color for each letter in a field. Each color is chosen from lighter colors when night mode is enabled, and from darker colors otherwise.

<div id="front-field" hidden>{{Front}}</div>
<script>
    var fieldID = "front-field";
    var randomHsl = (isNightMode) => {
        const hue = (Math.random() * 361) | 0;
        const saturation = (Math.random() * 101) | 0;
        let lightness = (Math.random() * 51) | 0;
        if (isNightMode) {
            lightness += 50;
        }
        return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
    };
    var colorizeEachChar = (fieldId) => {
        const text = document.getElementById(fieldId).textContent;
        const nightMode = document.body.classList.contains("night_mode");
        const resultArray = [];
        for (const char of text) {
            if (/\S/.test(char)) {
                resultArray.push(
                    `<span style="color: ${randomHsl(nightMode)};">${char}</span>`
                );
            } else {
                resultArray.push(" ");
            }
        }
        return resultArray.join("");
    };
    setTimeout(() => {
        const ele = document.getElementById(fieldID);
        ele.innerHTML = colorizeEachChar(fieldID);
        ele.hidden = false;
    }, 0);
</script>

3 Likes

Works wonderfully! Thanks so much.

1 Like

Is it possible to implement this for multiple fields? When I try to add more fields it randomizes only one at a time and the other one stays black. It always randomizes the same one too.
This is my current “mega random” script which randomizes everything including the font: