MediaWiki:Gadget-SidebarTOC.js

Revision as of 17:46, 22 February 2024 by Makko Oko (talk | contribs)
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)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
$(function(){
    if (!$('#toc').length) {
        return;
    }
    var i18n = {
        header: 'Contents',
        top: '(Top)'
    };

    // Remove the existing TOC
    $('#toc').remove();

    // Create a new TOC
    var $tocList = $('<ul class="vector-menu-content-list">').append(
        $('<li class="toclevel-1 tocsection-0">').append($('<a href="#">').append(
            $('<span class="toctext">').text(i18n.top)
        )),
        $('#content > h2, #content > h3, #content > h4, #content > h5, #content > h6').map(function() {
            var $this = $(this);
            return $('<li class="toclevel-' + this.tagName.slice(1) + '">').append(
                $('<a href="#' + this.id + '">').text($this.text())
            );
        })
    );

    // Append the new TOC to the page
    $('<nav id="p-toc" class="vector-menu mw-portlet mw-portlet-toc vector-menu-portal portal" aria-labelledby="p-toc-label" role="navigation">').append(
        $('<h3 id="p-toc-label" class="vector-menu-heading" tabindex="0">').append(
            $('<span class="vector-menu-heading-label">').text(i18n.header)
        ),
        $('<div class="vector-menu-content">').append($tocList)
    ).appendTo('#mw-panel');

    // Ensure that the "Contents" header still follows the user when scrolling
    var $pToc = $('#p-toc');
    $(window).on('scroll', function() {
        var scrollTop = $(this).scrollTop();
        if (scrollTop > 100) {
            $pToc.css('top', scrollTop - 100);
        } else {
            $pToc.css('top', 0);
        }
    });

    // Prevent the TOC from collapsing immediately after opening it
    $pToc.on('click', function(event) {
        event.stopPropagation();
        $pToc.toggleClass('collapsed');
    });
});