MediaWiki:Gadget-main-trivia-box.js

From Rhythm Game Wiki
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* Finds elements by a selector and executes a function for each element */
function findAndExecute(selector, callback) {
    const elements = document.querySelectorAll(selector);
    elements.forEach((element) => {
        try {
            callback(element);
        } catch (e) {
            console.error(`Error while initializing "${selector}"`, e);
        }
    });
}

/* Template:TriviaBox */

findAndExecute(".rgwiki-main-trivia-box", (div) => {
    function roll() {
        div.querySelectorAll("li.rgwiki-main-trivia-active").forEach(x => { x.classList.remove("rgwiki-main-trivia-active"); x.classList.add("rgwiki-main-trivia-previously-active"); });

        const elements = div.querySelectorAll("li:not(.rgwiki-main-trivia-previously-active");
        if (elements.length !== 0) {
            const rand = Math.floor(Math.random() * elements.length);
            elements[rand].classList.add("rgwiki-main-trivia-active");
        }

        div.querySelectorAll("li.rgwiki-main-trivia-previously-active").forEach(x => { x.classList.remove("rgwiki-main-trivia-previously-active"); });
    }
    const buttons = div.querySelector(".rgwiki-main-trivia-buttons");
    const a = buttons.querySelector(".rgwiki-main-trivia-reroll");
    a.addEventListener("click", roll);
    roll();
});