Skip to content

Commit

Permalink
Added the click to copy feature for code blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
tarunsinghofficial committed Mar 4, 2024
1 parent 61bb5c1 commit 7b350e0
Showing 1 changed file with 36 additions and 3 deletions.
39 changes: 36 additions & 3 deletions src/_layouts/default.erb
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
<body class="flex min-h-full bg-white antialiased dark:bg-zinc-900" x-data="{nav_open: false}" :class="{'overflow-hidden': nav_open}">
<div class="w-full">
<div class="h-full lg:ml-72 xl:ml-80">
<header
class="contents lg:pointer-events-none lg:fixed lg:inset-0 lg:z-40 lg:flex"
>
<header class="contents lg:pointer-events-none lg:fixed lg:inset-0 lg:z-40 lg:flex">
<div class="contents lg:pointer-events-auto lg:block lg:w-72 lg:overflow-y-auto lg:border-r lg:border-zinc-900/10 xl:w-80 lg:dark:border-white/10">
<div class="hidden lg:flex sticky top-0 z-20 py-2 px-6 backdrop-blur-sm dark:backdrop-blur bg-white/[var(--bg-opacity-light)] dark:bg-zinc-900/[var(--bg-opacity-dark)]" style="--bg-opacity-light:0.5;--bg-opacity-dark:0.2">
<%= render 'site_logo' %>
Expand All @@ -34,5 +32,40 @@
</div>
</div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function(event) {
const codeBlocks = document.querySelectorAll('pre code');
codeBlocks.forEach(function(block) {
const pre = block.parentNode;
const copyButton = document.createElement('button');
copyButton.innerHTML = 'Copy';
copyButton.classList.add('copy-button');
pre.appendChild(copyButton);

copyButton.addEventListener('click', function() {
const contentToCopy = block.innerText;
const tempTextarea = document.createElement('textarea');
tempTextarea.value = contentToCopy;
document.body.appendChild(tempTextarea);
tempTextarea.select();
document.execCommand('copy');
document.body.removeChild(tempTextarea);
copyButton.innerHTML = 'Copied!';
setTimeout(function() {
copyButton.innerHTML = 'Copy';
}, 2000);
});

pre.addEventListener('mouseenter', function() {
copyButton.style.display = 'inline-block';
});

pre.addEventListener('mouseleave', function() {
copyButton.style.display = 'none';
});
});
});
</script>
</body>
</html>

0 comments on commit 7b350e0

Please sign in to comment.