-
Notifications
You must be signed in to change notification settings - Fork 362
/
Copy pathindex.js
70 lines (55 loc) · 2.38 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import tippy from 'tippy.js'
export default function () {
// get the list of all highlight code blocks
const highlights = document.querySelectorAll("div.highlighter-rouge")
highlights.forEach(div => {
// create the copy button
const copy = document.createElement("button")
copy.innerHTML = "<img src='/docs/images/duplicate.svg' />"
// add the event listener to each click
copy.addEventListener("click", handleCopyClick)
// append the copy button to each code block
div.append(copy)
})
const copyToClipboard = str => {
const el = document.createElement("textarea") // Create a <textarea> element
el.value = str // Set its value to the string that you want copied
el.setAttribute("readonly", "") // Make it readonly to be tamper-proof
el.style.position = "absolute"
el.style.left = "-9999px" // Move outside the screen to make it invisible
document.body.appendChild(el) // Append the <textarea> element to the HTML document
const selected =
document.getSelection().rangeCount > 0 // Check if there is any content selected previously
?
document.getSelection().getRangeAt(0) // Store selection if found
:
false // Mark as false to know no selection existed before
el.select() // Select the <textarea> content
document.execCommand("copy") // Copy - only works as a result of a user action (e.g. click events)
document.body.removeChild(el) // Remove the <textarea> element
if (selected) {
// If a selection existed before copying
document.getSelection().removeAllRanges() // Unselect everything on the HTML document
document.getSelection().addRange(selected) // Restore the original selection
}
}
function handleCopyClick(evt) {
// get the children of the parent element
const {
children
} = evt.target.parentElement.parentElement
// grab the first element (we append the copy button on afterwards, so the first will be the code element)
// destructure the innerText from the code block
const {
innerText
} = Array.from(children)[0]
// copy all of the code to the clipboard
copyToClipboard(innerText)
// alert to show it worked, but you can put any kind of tooltip/popup to notify it worked
const alert = children[1]
alert.classList.add("green")
setTimeout(() => {
alert.classList.remove("green")
}, 700)
}
}