Skip to content

Instantly share code, notes, and snippets.

@rf5860
Last active June 12, 2024 17:23
Show Gist options
  • Save rf5860/cd139a501ac057b8bba283d0b48f5bac to your computer and use it in GitHub Desktop.
Save rf5860/cd139a501ac057b8bba283d0b48f5bac to your computer and use it in GitHub Desktop.
Adds a clipboard icon to code elements for easy copying on superuser.com
// ==UserScript==
// @name SuperUser Copy Code
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Adds a clipboard icon to code elements for easy copying
// @author rf5860
// @match *://superuser.com/*
// @downloadURL https://gist.github.com/rf5860/cd139a501ac057b8bba283d0b48f5bac/raw/SuperUser_CopyCode.user.js
// @updateURL https://gist.github.com/rf5860/cd139a501ac057b8bba283d0b48f5bac/raw/SuperUser_CopyCode.user.js
// @grant GM_setClipboard
// ==/UserScript==
(function () {
'use strict';
// Unicode clipboard icon
const clipboardIcon = '📋';
// Select all pre elements
const preElements = document.querySelectorAll('pre');
// Iterate over each pre element
preElements.forEach((pre) => {
// Ensure the pre element is positioned relatively
pre.style.position = 'relative';
// Create a new span element for the clipboard icon
const span = document.createElement('span');
span.textContent = clipboardIcon;
span.style.position = 'absolute';
span.style.top = '5px'; // Adjust vertical position as needed
span.style.right = '5px'; // Position the icon on the far right
span.style.cursor = 'pointer';
span.style.zIndex = '1'; // Ensure the icon is above the code block
// Add a click event listener to the span
span.addEventListener('click', () => {
// Set the clipboard to the contents of the code block within the pre element
GM_setClipboard(pre.querySelector('code').textContent);
});
// Add the span to the pre element
pre.appendChild(span);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment