Jump to content

User:Polygnotus/Scripts/Jump.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Add a button on the top border of #content that scrolls to and highlights
// the first occurrence of the username as visible text within #content.
// The button only appears if such an occurrence actually exists.
(function () {
    var content = document.getElementById('content');
    if (!content) return;

    var username = mw.config.get('wgUserName');
    if (!username) return;

    // Walk text nodes in #content to find the first visible occurrence
    var walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT, null, false);
    var targetNode = null;
    while (walker.nextNode()) {
        if (walker.currentNode.nodeValue.indexOf(username) !== -1) {
            targetNode = walker.currentNode.parentElement;
            break;
        }
    }

    // Username not found as visible text in #content — do nothing
    if (!targetNode) return;

    if (window.getComputedStyle(content).position === 'static') {
        content.style.position = 'relative';
    }

    var btn = document.createElement('button');
    btn.textContent = username;
    btn.style.cssText = [
        'position: absolute',
        'top: -1px',
        'left: 50%',
        'transform: translateX(-50%)',
        'z-index: 10',
        'padding: 1px 10px',
        'font-size: 12px',
        'cursor: pointer',
        'background: #f8f9fa',
        'border: 1px solid #a2a9b1',
        'border-top: none',
        'border-radius: 0 0 4px 4px',
        'color: #202122'
    ].join(';');

    btn.addEventListener('click', function () {
        targetNode.style.boxShadow = '0 0 0 2px red';
        setTimeout(function () {
            targetNode.style.boxShadow = '';
        }, 2000);
        targetNode.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });

    content.insertBefore(btn, content.firstChild);
})();