Photo by Markus Spiske on Unsplash

Code: Codemirror and copy to clipboard

While working on a Form-Builder for Helpmonks, so our users can just copy & paste the HTML into their pages, I’ve re-used Codemirror.

I’m not the biggest fan of the project, but once configured it mainly works well. However, they don’t seem to believe in adding features that someone would find to “make sense”. One of those is that they don’t provide a copy function.

Hence, this small snippet, which I’ve figured out after some time. Hope this helps someone. I’m using clipboard.js here with a simple button.

The issue is that you cannot just use the ID of the textarea to copy the content, hence you can use the “text” callback of the clipboard library.

Enough talk, here is the code:

var cm = CodeMirror.fromTextArea(document.getElementById('id_textarea'), {
styleActiveLine: true,
lineNumbers: true,
matchBrackets: true,
mode: "text/html",
viewportMargin: Infinity

Once Codemirror is initialized, we can add the clipboard code that grabs the value from Codemirror’s textarea:

var _clip = new Clipboard('id_button', {
text: function(trigger) {
return cm.getValue();

Finally, you can add an event to notify the user that the content has been copied to the clipboard:

_clip.on('success', function (e) {

I hope this helps someone else. Cheers.