Using clipboard.js , you can define the text() function to capture the value of the internal code of a CodeMirror document.
Save the selector link ( <textarea> ) for convenience.
var editorSelector = '#editor'
Create a new ClipBoard object with a link to your button.
new Clipboard('.clip-btn-native', { text: function(trigger) { return getCodeMirrorNative(editorSelector).getDoc().getValue(); } });
Get an instance of CodeMirror through native JavaScript.
function getCodeMirrorNative(target) { var _target = target; if (typeof _target === 'string') { _target = document.querySelector(_target); } if (_target === null || !_target.tagName === undefined) { throw new Error('Element does not reference a CodeMirror instance.'); } if (_target.className.indexOf('CodeMirror') > -1) { return _target.CodeMirror; } if (_target.tagName === 'TEXTAREA') { return _target.nextSibling.CodeMirror; } return null; };
Demo
See full; in-depth demo on JSFiddle .
source share