JavaScript Copy()
The JavaScript copy()
method is used to copy the text or content to the clipboard. It is commonly used while building applications where users can copy data from one source to another, like copying a link to a web page, email address, or other text content.
Syntax
document.copy();
Example
function copyText() {
const copyContent = document.getElementById("text");
copyContent.select();
document.execCommand("copy");
alert("Text Copied: " + copyContent.value);
}
Explanation
First, we define a function copyText()
that contains our logic for copying the content. This function is triggered when an element like a button is clicked.
Next, we grab the text content that we want to copy using document.getElementById()
and storing it in the copyContent
variable.
Now, we use the select()
method to select the text inside the input field. Then we use the execCommand()
method, which is used to execute a certain command such as copy, paste, cut, etc. In our case, we are using it to copy the selected text.
Finally, we show a message alert confirming that the text has been copied.
Use
The copy()
method is widely used while building web applications where user interaction is required to perform an action. For instance, if we are building an application that involves sharing data like a web page link, email address, or other text content, we can use copy()
to enable users to easily copy that content with just a click of a button.
Important Points
- The
copy()
method is only triggered when executed within a user-initiated event such as aclick
event, or akeydown
event. - The
document.execCommand('copy')
method is not supported in some browsers like Safari, in which case, we can use the Clipboard API provided by modern browsers.
Summary
The copy()
method is commonly used while building web applications to enable users to easily copy text content like web page links, email addresses, or other text content to the clipboard. This method requires a user-initiated event like a button click and uses the document.execCommand()
method to execute the copy
command. The method is not supported in some older browsers like Safari, in which case, the Clipboard API can be used.