The current code appends a button to quickly select some code in a <pre>
tag. What I want to add is the ability to copy that content to the clipboard and change the button text to "copied".
How can I achieve it by modifying the current working code below? I wouldn't mind using clipboard.js, jQuery bits or just native JS support as it was introduced since Chrome 43. I just dont know how to go on from here on adding what I need.
function selectPre(e) {
if (window.getSelection) {
var s = window.getSelection();
if (s.setBaseAndExtent) {
s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
}
else {
var r = document.createRange();
r.setStart(e.firstChild, 0);
r.setEnd(e.lastChild, e.lastChild.textContent.length);
s.removeAllRanges();
s.addRange(r);
}
}
else if (document.getSelection) {
var s = document.getSelection();
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
else if (document.selection) {
var r = document.body.createTextRange();
r.moveToElementText(e);
r.select();
}
}
var diff = document.getElementById('diff_table').getElementsByTagName('tr');
var difflen = diff.length;
for(i=0; i<difflen; i++) {
var newdiff = diff[i].childNodes[1];
if (newdiff.className && (newdiff.className == 'added' || newdiff.className == 'modified')) {
newdiff.className += ' diff-select';
newdiff.innerHTML = '<div class="btnbox"><button class="btn btn-default btn-xs" onclick="selectPre(this.parentNode.nextSibling)">Select</button></div>' + newdiff.innerHTML;
}
}