-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add 'copy code to clipboard' button to code blocks
- Loading branch information
1 parent
6e0fd4b
commit 859cecb
Showing
4 changed files
with
60 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
// Source: https://www.roboleary.net/2022/01/13/copy-code-to-clipboard-blog.html | ||
// | ||
const copyButtonLabel = "Copy Code"; | ||
const copiedButtonLabel = "Code Copied"; | ||
|
||
// use a class selector if available | ||
const blocks = document.querySelectorAll("pre"); | ||
|
||
blocks.forEach((block) => { | ||
// only add button if browser supports Clipboard API | ||
if (navigator.clipboard) { | ||
const button = document.createElement("button"); | ||
|
||
button.innerText = copyButtonLabel; | ||
block.appendChild(button); | ||
|
||
button.addEventListener("click", async () => { | ||
await copyCode(block, button); | ||
}); | ||
} | ||
}); | ||
|
||
async function copyCode(block, button) { | ||
const code = block.querySelector("code"); | ||
const text = code.innerText; | ||
await navigator.clipboard.writeText(text) | ||
.then(() => { | ||
// visual feedback that task is completed | ||
button.innerText = copiedButtonLabel; | ||
|
||
setTimeout(() => { | ||
button.innerText = copyButtonLabel; | ||
}, 1e3); | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters