add copy to clipboard functionality

This commit is contained in:
Stefan Feješ
2017-12-23 16:00:07 +01:00
parent fd6d33c493
commit 0721ebd375
2 changed files with 34 additions and 5 deletions

View File

@ -1,11 +1,20 @@
var s = document.querySelectorAll("pre");
s.forEach(element => {
var button = document.createElement("button");
var pres = document.querySelectorAll("pre");
pres.forEach(element => {
const button = document.createElement("button");
button.innerHTML = "Copy to clipboard";
element.parentElement.appendChild(button);
button.addEventListener ("click", function() {
var text = element.textContent.replace(/\/\*(.|[\r\n])*?\*\//g, '').replace(/\/\/.*/gm, '');
console.log(text);
//The following regex removes all the comments from the snippet
const text = element.textContent.replace(/\/\*(.|[\r\n])*?\*\//g, '').replace(/\/\/.*/gm, '');
// Apparently you can copy variable to clipboard so you need to create text input element,
// give it a value, copy it and then remove it
const textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
document.body.removeChild(textArea);
console.log(`copied: ${text}`);
});
});