20 lines of JS Code to achieve clipboard copy, 20 lines of js

Source: Internet
Author: User
Tags try catch

20 lines of JS Code to achieve clipboard copy, 20 lines of js

Using clipboard is a basic skill. You should know that Tab, Ctrl/Cmd + A, Ctrl/Cmd + C, and Ctrl/Cmd + V are shortcut keys for automatic focus, copy, and paste.

It may not be easy for common users. Even if users know what the clipboard is, it is difficult to highlight the exact text they want in other cases, except for those who have an excellent eye or quick response. If the user does not know the keyboard shortcut, does not see the hidden editing menu, or does not use the right-click menu or does not know the long-press touch screen pop-up option menu, then he may not be aware of the copy function.

Should we provide a "Copy to clipboard" button to help users? This function should be useful, even for users who are very familiar with shortcuts.

Security of clipboard

A few years ago, the browser could not directly use the clipboard. Developers have to use Flash.

The clipboard does not seem to matter, but imagine what will happen if the browser can view and manipulate the content at will. JS scripts (including third-party scripts) can view the text information in the clipboard, and send the password, sensitive information, and even the entire document to the remote server.

The basic functions of the clipboard are limited as follows:

  1. Most browsers support clipboard except Safari.
  2. Different browsers are supported, and some functions are incomplete or problematic.
  3. The event must be initiated by the user, such as clicking the mouse or pressing the keyboard. The script cannot access the clipboard freely.

document.execCommand()

This method is the key to clipboard implementation. It can input cut, copy and paste parameters. Fromdocument.execCommand('copy')Start with introduction.

Before use, we should check whether the browser supports the copy command:document.queryCommandSupported('copy'); Ordocument.queryCommandEnabled('copy'); The two methods have the same effect.

However, in Chrome, although Chrome does support the use of copy naming, both methods return false. Therefore, it is best to include the check code in a try-catch code block.

Next, what should we allow users to copy? The text must be highlighted. all browsers can use the select () method to select text input and text in textarea. Firefox and Chrome/Opera also support document.createRange Method, which allows you to select text from any element, as follows:

// select text in #myelement node  var   myelement = document.getElementById('#myelement'),   range = document.createRange();  range.selectNode(myelement);  window.getSelection().addRange(range);

However, IE/Edge does not.

Clipboard. js

If you don't want to implement a more robust cross-browser clipboard method, clipboard. js can help you. It has several setting options, such as the data attribute of H5, setting the binding trigger element and target element, such:

<input id="copyme" value="text in this field will be copied" /><button data-clipboard-target="#copyme">copy</button>

Implement it by yourself

Clipboard. js is only 2 kb in size. If you only implement the following functions, You can implement it in 20 lines of code:

Only some form elements can be copied

If not supported browsers (that is, Safari), you can highlight the selected text and prompt the user to press Ctrl/Cmd + C.

Like clipboard. js, create a button to trigger the method. It has a data-copytarget attribute and points to the element to be copied (that is, # website)

<Input type = "text" id = "website" value = "http://www.sitepoint.com/"/> <button data-copytarget = "# website"> copy </button> an immediate execution function function used to bind a click event to an expression, this function is used to parse the data-copytarget attribute content, select the text of the corresponding field, and execute document.exe cCommand ('copy '),. If it fails, the text remains selected, and a prompt box is displayed: (function () {'use strict '; // click events document. body. addEventListener ('click', copy, true); // event handler function copy (e) {// find target element var t = e.tar get, c = t. dataset. copytarget, indium = (c? Document. querySelector (c): null); // is element selectable? If (indium & indium. select) {// select text indium. select (); try {// copy text document.exe cCommand ('copy'); indium. blur () ;}catch (err) {alert ('Please press Ctrl/Cmd + C to copy ');}}}})();

Example

In the above example, there are more than 20 lines of code for the style and animation, but the animation and style are optional.

Summary:

  1. Use. select () to select the content of the form element to be copied
  2. Call document.exe cCommand ("copy ")
  3. Call the. blur () method to remove the focus from the form element.
  4. Add steps 2nd and 3 to the try catch block, and the prompt is displayed in an unsupported browser.

Other methods

There are many novel clipboard applications. For example, when you hover the mouse over a card, you can press Ctrl / Cmd + C And copy the link address of the card to the clipboard. The implementation method is as follows: first create a hidden form element containing the URL, and then select and copy its content. Very clever and practical-I suspect few users know this function!

Summary

The above is the 20 lines of JS Code introduced by xiaobian to implement the clipboard copy function. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.