Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

MediaWiki:Gadget-copyCode.js

MediaWiki interface page
Revision as of 13:03, 22 August 2025 by Omgro (talk | contribs) (Created page with "mw.loader.using(['jquery']).then(function() { // Find all <code> elements $('code').each(function() { var $code = $(this); // Skip <code> inside <pre> or <syntaxhighlight> to avoid conflicts if ($code.parents('pre, .mw-highlight').length === 0) { // Create a wrapper div for positioning var $wrapper = $('<div>').css({ 'position': 'relative', 'display': 'inline-block' });...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.
mw.loader.using(['jquery']).then(function() {
    // Find all <code> elements
    $('code').each(function() {
        var $code = $(this);
        // Skip <code> inside <pre> or <syntaxhighlight> to avoid conflicts
        if ($code.parents('pre, .mw-highlight').length === 0) {
            // Create a wrapper div for positioning
            var $wrapper = $('<div>').css({
                'position': 'relative',
                'display': 'inline-block'
            });
            // Create the copy button
            var $button = $('<button>').text('Copy').css({
                'position': 'absolute',
                'top': '0',
                'right': '0',
                'margin': '2px',
                'padding': '2px 6px',
                'font-size': '12px',
                'cursor': 'pointer'
            });
            // Add click event to copy text
            $button.on('click', function() {
                var text = $code.text();
                navigator.clipboard.writeText(text).then(function() {
                    $button.text('Copied!');
                    setTimeout(function() {
                        $button.text('Copy');
                    }, 1000); // Reset after 1 second
                }).catch(function(err) {
                    console.error('Copy failed:', err);
                    $button.text('Error');
                });
            });
            // Wrap the <code> element and append the button
            $code.wrap($wrapper).after($button);
        }
    });
});