Jump to content

Module:ExtendedSwitcher

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Orca (talk | contribs) at 19:21, 14 March 2025 (Switcher with more than 20 elements - test). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
local p = {}

function p.main(frame)
    local root = mw.html.create('div'):addClass('switcher-container')
    local default = tonumber(frame.args.default) or 1  -- Default option (1-based index)
    
    local buttonContainer = root:tag('div'):addClass('switcher-buttons')  -- Div for switcher buttons
    local contentContainer = root:tag('div'):addClass('switcher-contents') -- Div for switcher contents
    
    for i = 1, #frame.args, 2 do
        local label = frame.args[i]
        local content = frame.args[i + 1] or ""

        if label then
            -- Create switcher buttons
            buttonContainer:tag('button')
                :attr('onclick', 'switchContent(' .. i .. ')')
                :wikitext(label)

            -- Create switcher content areas
            local contentDiv = contentContainer:tag('div')
                :addClass('switcher-content')
                :attr('id', 'switcher-' .. i)
                :wikitext(content)

            if i == default * 2 - 1 then
                contentDiv:css('display', 'block')  -- Show default
            else
                contentDiv:css('display', 'none')   -- Hide others
            end
        end
    end

    -- Add JavaScript for switching behavior
    root:tag('script'):wikitext([[
        function switchContent(n) {
            var elements = document.getElementsByClassName('switcher-content');
            for (var i = 0; i < elements.length; i++) {
                elements[i].style.display = 'none';
            }
            document.getElementById('switcher-' + n).style.display = 'block';
        }
    ]])

    return root
end

return p