Easy way to add 'copy to clipboard' to GitHub markdown?

Specifically, I have blocks of code for install that I want the user to be able to quickly copy and paste into a terminal. I'd like a button to 'copy to clipboard' for the code block. Since there's a 'copy to clipboard' button for the git clone URLs, I was wondering if I could piggy back off that or if not whether there was some relatively simple I could add to the MD to make this happen. Or is this simply not possible with the processing and 'safication' the MD text goes through?

9

3 Answers

The copy button is now a reality (May 2021), as tweeted by Nat Friedman

We just added a "Copy" button to all code blocks on GitHub.

Copy

To create a copy button, make a Fenced code block as shown here, in a markdown document

function test() { console.log("This code will have a copy button to the right of it");
}
5

I think that it is not what you want, but if you want to copy, you can do it by running the bookmarklet and adding a copy button.

var copy = function(target) { var textArea = document.createElement('textarea') textArea.setAttribute('style','width:1px;border:0;opacity:0;') document.body.appendChild(textArea) textArea.value = target.innerHTML textArea.select() document.execCommand('copy') document.body.removeChild(textArea)
}
var pres = document.querySelectorAll(".comment-body > pre")
pres.forEach(function(pre){ var button = document.createElement("button") button.className = "btn btn-sm" button.innerHTML = "copy" pre.parentNode.insertBefore(button, pre) button.addEventListener('click', function(e){ e.preventDefault() copy(pre.childNodes[0]) })
})
3

This is probably the most straightforward way I know of.

So all you have to do is Any Header/subtitle or any text you want starting with hash, then in the next line, you add your copyable text like below,

[Hash Sign(#)][Space]Any Header/subtitle or any text you want starting with hash
[Tab][Tab]Your text

This should look like this.

Example 1:

To create a copyable code block, create a Header like this. Then put two tab gaps

YourCopyableTextblock

Example 2:

To create a copyable code block, create a comment like this. Then put two tab gaps
YourCopyableTextblock

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like