Upgrade to Pro

JavaScript Snippet That Displays a Copy Icon In code block

Here's an advanced JavaScript snippet that displays a copy icon next to a code block, allowing users to easily copy the snippet source code. It includes modern CSS for styling, tooltips, animations, and works dynamically for multiple code blocks on a page.

 Features:

  • Copy icon appears on hover.

  • Tooltip on click: “Copied!” feedback.

  • Works with multiple <pre><code> blocks.

  • Clean, minimal, and modern look.

 HTML Example

<pre><code class="code-snippet">console.log("Hello, World!");</code></pre>
<pre><code class="code-snippet">const sum = (a, b) => a + b;</code></pre>

 CSS (Advanced Style)

<style>
.code-container {
  position: relative;
  display: inline-block;
  width: 100%;
}
.copy-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  background: #f0f0f0;
  border: none;
  padding: 6px;
  border-radius: 8px;
  cursor: pointer;
  display: none;
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
  transition: transform 0.2s;
}
.copy-btn:hover {
  transform: scale(1.1);
}
.copy-tooltip {
  position: absolute;
  top: -30px;
  right: 8px;
  background: #4caf50;
  color: white;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  display: none;
}
.code-container:hover .copy-btn {
  display: block;
}
pre {
  background: #272822;
  color: #f8f8f2;
  padding: 16px;
  border-radius: 10px;
  overflow-x: auto;
}
</style>

JavaScript

<script>
document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll("code.code-snippet").forEach((codeBlock) => {
    // Wrap in a container
    const wrapper = document.createElement("div");
    wrapper.className = "code-container";

    const pre = codeBlock.parentNode;
    pre.parentNode.insertBefore(wrapper, pre);
    wrapper.appendChild(pre);

    // Create copy button
    const copyBtn = document.createElement("button");
    copyBtn.className = "copy-btn";
    copyBtn.innerHTML = "📋";
    wrapper.appendChild(copyBtn);

    // Tooltip
    const tooltip = document.createElement("div");
    tooltip.className = "copy-tooltip";
    tooltip.textContent = "Copied!";
    wrapper.appendChild(tooltip);

    copyBtn.addEventListener("click", () => {
      navigator.clipboard.writeText(codeBlock.innerText).then(() => {
        tooltip.style.display = "block";
        setTimeout(() => {
          tooltip.style.display = "none";
        }, 1500);
      });
    });
  });
});
</script>

 

Flowisetech For easy access