Skip to content

Instantly share code, notes, and snippets.

@sskanishk
Last active May 27, 2021 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sskanishk/b8715ebd77bc2a3bf91606230bcf55ab to your computer and use it in GitHub Desktop.
Save sskanishk/b8715ebd77bc2a3bf91606230bcf55ab to your computer and use it in GitHub Desktop.
Code Snippet Code to Clipboard button functionality on code snippet.
// it is written for below structure
<pre>
<code>
----some----code----
</code>
<pre>
function CopyToClipboard(params) {
const codeContainer = document.getElementsByTagName('pre');
// debugger
for (const item of codeContainer) {
const button = document.createElement('button');
button.innerText = 'Copy';
button.style.position = 'absolute';
button.style.top = "0";
button.style.right = "0";
button.style.fontSize = "10px";
button.style.border = "none";
button.style.background = "gainsboro";
button.style.borderRadius = "0px 3px 0px 3px";
button.className = 'copy-btn';
button.onclick = function () {
let x = item.firstChild.textContent
console.log('iiner', x)
const el = document.createElement('textarea');
el.value = x;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
button.innerText = 'Copied';
setTimeout(() => {
button.innerText = 'Copy';
}, 1000);
};
item.append(button);
}
}
export default CopyToClipboard;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment