JavaScript has an easy solution to copy text to the clipboard. If your website contains text that users want to copy, you can add a button to make the process effortless.
You'll learn how to leverage JavaScript's capabilities to enable seamless text copying to your clipboard. It will provide an excellent user experience and ease of use.
Whether you want to copy input values, specific text, or even content from HTML elements, we've got you covered. You can use our technique to do all of these.
Copying Text to The Clipboard Using JavaScript
To copy text to the clipboard using JavaScript, utilize the writeText()
method from the navigator.clipboard
API. Simply call the writeText()
method and pass the text you want to copy as an argument. Your text will be copied to the clipboard.
You can directly pass a string, template literal, or a variable that holds a string. This method also works asynchronously which means it doesn't block the main thread.
Also Read: Synchronous VS Asynchronous Programming with Examples
Traditionally, copying text to the clipboard in JavaScript involved using the document.execCommand('copy')
function. However, this approach is becoming deprecated and has limited browser support.
That's why we will use the navigator.clipboard
API. It offers a more robust solution and better result.
const copyTextToClipboard = async (text) => {
try {
await navigator.clipboard.writeText(text)
console.log('Text copied to clipboard successfully!')
} catch (error) {
console.error('Failed to copy text:', error)
}
}
const textToCopy = 'Hello, World!'
copyTextToClipboard(textToCopy)
In this example, we have defined the copyTextToClipboard
function that takes a text
parameter. We call the writeText()
method from the navigator.clipboard
API, passing the desired text
as an argument.
The method works asynchronously and returns a promise. Therefore we can use the async/await syntax with try...catch
block to handle any unwanted errors.
This approach provides a more consistent and reliable way to copy text to the clipboard across different browsers.
Also Read: How to Generate Random Secure Passwords Using JavaScript
How to Copy Input Value to The Clipboard on Button Click
Copying input values to the clipboard is a common use case, especially in web forms or data-driven applications. With JavaScript, you can easily implement the functionality to copy input values on a button click.
You can do this using the technique that you have seen in the previous section.
<input type="text" id="inputField" />
<button id="copyButton">Copy</button>
Suppose you have an <input>
element with some text in it. You want to add a functionality to a button so that when someone clicks it, the text in the input field will be copied to the clipboard.
Let's see how we can achieve this using JavaScript navigator.clipboard
API.
const inputField = document.getElementById('inputField')
const copyButton = document.getElementById('copyButton')
const copyTextToClipboard = async (text) => {
try {
await navigator.clipboard.writeText(text)
console.log('Text copied to clipboard successfully!')
} catch (error) {
console.error('Failed to copy text:', error)
}
}
copyButton.addEventListener('click', () => {
const textToCopy = inputField.value // Getting text from input field
copyTextToClipboard(textToCopy) // Copying text from clipboard
})
First, we select the <input>
and <button>
element in JavaScript using the getElementById()
method. We use JavaScript to listen for a click
event on the button.
When the button gets clicked, we will retrieve the value of the input field using inputField.value
and pass it to the copyTextToClipboard
function.
We have created this function in the previous section. You can use the same function here to copy the input value. It uses the writeText()
method from the navigator.clipboard
API.
This way, you can easily copy the input value by clicking the copy button.
Also Read: How to Sanitize User Input in JavaScript: Prevent XSS Attack
How to Copy Text to The Clipboard From Any HTML Elements
Not only input fields, you can also copy text from any HTML elements using this technique. JavaScript allows you to extract text from these elements and copy it to the clipboard.
Suppose you have a paragraph element with the id paragraph
and you want to copy the text from this element by clicking a button.
<p id="paragraph">Example Text</p>
<button id="copyButton">Copy</button>
First, select the <p>
and <button>
element using the getElementById()
method in your JavaScript file. Listen to the click
event to the button element.
const paragraph = document.getElementById('paragraph')
const copyButton = document.getElementById('copyButton')
const copyTextToClipboard = async (text) => {
try {
await navigator.clipboard.writeText(text)
console.log('Text copied to clipboard successfully!')
} catch (error) {
console.error('Failed to copy text:', error)
}
}
copyButton.addEventListener('click', () => {
const textToCopy = paragraph.innerText // Getting text from paragraph element
copyTextToClipboard(textToCopy) // Copying text from clipboard
})
When the copy button gets clicked, we retrieve the text content of the paragraph element using paragraph.innerText
and pass it to the copyTextToClipboard
function.
This function will copy the text from the paragraph to the clipboard using the writeText()
method from the navigator.clipboard
API.
Also Read: How to Get The Current Year in JavaScript Step-by-Step Guide
Conclusion
By leveraging the navigator.clipboard
API, you can achieve clipboard functionality with ease. Whether you need to copy specific text, input values, or content from HTML elements, call the writeText()
method from it.
It also provides better performance because it works asynchronously. Now you can add a button on your page to copy a specific text to your clipboard using JavaScript.