You've probably noticed by now that this blog has lots of snippets that you want to copy into a script before executing. It would be convenient if you didn't have to manually select all of the text to copy it into your clipboard.
Up until now I've ignored adding this capability because I had understood that this capability required flash. However, we can now use clipboard.js to simplify the adding of this functionality. You can see that I have now implemented it into this blog with a link at the bottom of all code snippets that you can click to copy the snippet to your clipboard.
The clipboard.js site has a lot of great examples, but I wanted to bury something into my
pre elements and didn't want to use a button, so I took it a bit further and have put an example below that you can use/extend. The example below is pretty ugly, but its mostly going to be a matter of applying your own much better CSS to it. The key things are that it
- Uses a CDN to fetch the library, so you don't have to worry about adding the source code to something like a blog that you might not have access to the files on.
- Ensures that the "copy to clipboard" text itself isn't accidentally copied by the user.
- Parses the snippet to convert it back to html code in case you sanitized it for rendering on a web page like I have done.
In the future, I want to replace the textual link with an icon that appears in the top right corner whenever you hover over the
pre element, but this is a quick fix for now.