MediaWiki:Vector.js
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)
- Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
// Function to add copy buttons to <syntaxhighlight> or <pre> blocks
function addCopyButtons() {
document.querySelectorAll("div.mw-highlight").forEach((block) => {
// Avoid adding duplicate buttons
if (block.querySelector(".copy-button")) return;
// Create the copy button
const button = document.createElement("button");
button.className = "copy-button";
button.textContent = "Copy";
// Add click event to copy the code
button.addEventListener("click", () => {
const code = block.innerText.trim(); // Get the text inside the block
navigator.clipboard.writeText(code).then(() => {
button.textContent = "Copied!";
setTimeout(() => (button.textContent = "Copy"), 2000);
});
});
// Style the button and append it to the block
button.style.position = "absolute";
button.style.top = "10px";
button.style.right = "10px";
button.style.backgroundColor = "#444";
button.style.color = "white";
button.style.border = "none";
button.style.borderRadius = "5px";
button.style.padding = "5px 10px";
button.style.cursor = "pointer";
button.style.fontSize = "12px";
block.style.position = "relative"; // Ensure the block is positioned relatively
block.style.paddingTop = "30px"; // Add space for the button
block.appendChild(button);
});
}
// Run the function on initial page load
document.addEventListener("DOMContentLoaded", addCopyButtons);
// Run the function whenever new content is added to the page
mw.hook("wikipage.content").add(addCopyButtons);