CopyButton.js + Tippy.js + Popper.js

Demo also uses Highlight.js and Water.css

Examples

print("Hello world")

# Hover over me
# comment
console.log("Hello world")

// Hover over me too!
// comment

Usage

Copy the dependencies below:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://unpkg.com/@popperjs/core@2"></script>
<script src="https://unpkg.com/tippy.js@6"></script>  
<script defer src="https://cdn.jsdelivr.net/gh/thatrandomperson5/copybutton.js@main/lib/copybutton.js"></script>

Optional dependcies:

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script defer>hljs.highlightAll();</script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">

After, that you can just use <pre><code class="docopy"> anywhere and it will have a copy button!

Configuration

data-copybutton-class

Configure the class that should be placed upon the copy button. Overridden by data-copybutton-html

/* data-copybutton-class="redbutton" */
.redbutton {
    background: red!important;
}

data-copybutton-icon

Configure the font-awsome icon classname. Not compatible with data-copybutton-html

# data-copybutton-icon="fa-solid fa-rocket"
print("Going to space!")

data-copybutton-html

Configure a js function call that returns an element. This will be the button. Not compatible with data-copybutton-icon

// data-copybutton-html="makeCoolButton()"
function makeCoolButton() {
    let button = document.createElement("button");
    button.innerHTML = `<i>Click to copy!</i>`;
    return button;
}

data-copybutton-message

Set the tooltip message when the copy button is clicked!

// data-copybutton-message="Thanks for copying!"
console.log("Copy to get a cool message!");

data-copybutton-pos

Sets the position of the copybutton. Can be one of these: topright, topleft, bottomright, bottomleft, midright and midleft.

# data-copybutton-pos="topright"
        
print("Hello world")
# data-copybutton-pos="topleft"
        
print("Hello world")
# data-copybutton-pos="bottomright"
        
print("Hello world")
# data-copybutton-pos="bottomleft"
        
print("Hello world")
# data-copybutton-pos="midright"
        
print("Hello world")
# data-copybutton-pos="midleft"
        
print("Hello world")

Global API

data-no-update

Placing this on the script tag will result in updateCopybutton() not being called on load. Using this means the defer attribute is not required and might cause problems.

function updateCopybutton()

Call this to scan and add copybuttons!