Sometimes, we want to copy a text string on click with JavaScript.
In this article, we’ll look at how to copy a text string on click with JavaScript.
Copy a Text String on Click with JavaScript
To copy a text string on click with JavaScript, we can call the document.execuCommand
to copy the text to the clipboard.
Then we can listen to the copy
event to get the copied text.
For instance, if we have:
<span>hello world</span>
Then we write:
const span = document.querySelector("span");
span.onclick = () => {
document.execCommand("copy");
}
span.addEventListener("copy", (event) => {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", span.textContent);
console.log(event.clipboardData.getData("text"))
}
});
We select the span element with document.querySelector
.
Then we set the span.onclick
property to a function that calls document.execCommand
with 'copy'
to copy the text content of the span.
Next, we call span.addEventListener
with 'copy'
to add a copy event listener.
The callback will run when we run document.execCommand("copy");
.
We get the clipboard data with the event.clipboardData.setData
to set the copied data to the textContent
of the span.
And then we can get the text data that’s copied to the clipboatd with the getData
method with 'text'
.
Conclusion
To copy a text string on click with JavaScript, we can call the document.execuCommand
to copy the text to the clipboard.
Then we can listen to the copy
event to get the copied text.