Jump to content

MediaWiki:Common.js

From Grantha
Revision as of 11:55, 13 April 2026 by Chandrashekars (talk | contribs)

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.
/* Grantha.io — scroll-spy for MW native TOC links */
(function () {
    'use strict';

    mw.hook('wikipage.content').add(function () {
        setTimeout(function () {

            /* Find TOC links — works with both sidebar and inline TOC */
            var tocLinks = Array.from(
                document.querySelectorAll('.vector-toc a, #toc a, .toc a')
            ).filter(function (a) {
                return a.href && a.href.indexOf('#') !== -1;
            });

            if (!tocLinks.length) return;

            var targets = tocLinks.map(function (a) {
                return document.getElementById(a.href.split('#')[1]);
            });

            function update() {
                var threshold = window.scrollY + 130;
                var active = 0;
                for (var i = 0; i < targets.length; i++) {
                    if (targets[i]) {
                        var el = targets[i], top = 0;
                        while (el) { top += el.offsetTop; el = el.offsetParent; }
                        if (top <= threshold) active = i;
                    }
                }
                tocLinks.forEach(function (a, i) {
                    a.style.color = (i === active) ? '#f57c00' : '';
                    a.style.fontWeight = (i === active) ? '600' : '';
                });
            }

            window.addEventListener('scroll', update, { passive: true });
            update();

        }, 400);
    });
}());