Use of clipboard.js to copy text to clipboard

A copy plug-in that needs to be used in the work is good for simple compatibility, because you can translate it yourself without finding the introduction of the Chinese version. The level is limited, not necessarily all according to the article. If you have any questions, you are welcome to make corrections! ______.
For a more intuitive display of usage, slightly modify the code so that you can see the effect of each code directly, referring to third-party addresses can be safely pulled to run locally.
Original address https://clipboardjs.com/

clipboard.js is able to copy text to the clipboard in a modern way, independent of Flash, framework, and only 3kb in size.

Why?
Copying text to the clipboard should be easy. It does not require many steps to configure or load hundreds of KBs size files. But most importantly, it should not rely on Flash or any bloated framework.
That's why clipboard.js exists.

install

You can do it in npm.

npm install clipboard --save

Or in the browser.

bower install clipboard --save

If you are not in package management, download a ZIP file clipboard.js.

Set up

First, introduce scripts from the dist folder (the path the user places scripts) or from Third Party Loading CDN Provider.
The path for the user to place the script: <script src="dist/clipboard.min.js"></script>
jsDelivr: <script src="https://cdn.jsdelivr.net/clip...;></script>
cdnjs: <script src="https://cdnjs.cloudflare.com/...;></script>
RawGit: <script src="https://cdn.rawgit.com/zenoro...;></script>

Now, you just need to instantiate it through a DOM selector, HTML element, or a list of HTML elements.

new Clipboard('.btn');

Internally, we need to get all matching element selectors and add event listeners to each of them. But guess what? If you have hundreds of matching element selectors, this operation will consume a lot of memory.
For this reason we use Event proxy Multiple event listeners are replaced by one listener. After all, Perfect.

Use

We're living a declarative renaissance. That's why we decided to make use of it. HTML5 data attributes To get better usability.

Copy text from another element

A common use case is to copy the content of another element. You can use it by adding a data-clipboard-target attribute to the trigger element.
Its value is included in another attribute of the element selector that will be matched.

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>constructor-nodelist</title>
        <script src="https://cdn.jsdelivr.net/clipboard.js/1.6.0/clipboard.min.js"></script>
    </head>

    <body>
        <!-- Target -->
        <input id="foo" value="https://github.com/zenorocha/clipboard.js.git">

        <!-- Trigger -->
        <button class="btn" data-clipboard-target="#foo">
            Copy to clipboard
        </button>
        <br/>
        <input type="" name="" id="" value="" placeholder="You can paste it here to see the effect."/>

        <!-- 3. Instantiate clipboard by passing a list of HTML elements -->
        <script>
            var btns = document.querySelectorAll('button');
            var clipboard = new Clipboard(btns);

            clipboard.on('success', function (e) {
                console.log(e);
            });

            clipboard.on('error', function (e) {
                console.log(e);
            });
        </script>
    </body>

</html>

Cut text from another element

In addition, you can define a data-clipboard-action attribute to specify if you want to copy or cut content.
If this property is omitted, replication will be used by default.

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>constructor-nodelist</title>
        <script src="https://cdn.jsdelivr.net/clipboard.js/1.6.0/clipboard.min.js"></script>
    </head>

    <body>
        <!-- Target -->
        <textarea id="bar">Mussum ipsum cacilds...</textarea>

        <!-- Trigger -->
        <button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
            Cut to clipboard
        </button>
        <br/>
        <input type="" name="" id="" value="" placeholder="You can paste it here to see the effect."/>

        <!-- 3. Instantiate clipboard by passing a list of HTML elements -->
        <script>
            var btns = document.querySelectorAll('button');
            var clipboard = new Clipboard(btns);

            clipboard.on('success', function (e) {
                console.log(e);
            });

            clipboard.on('error', function (e) {
                console.log(e);
            });
        </script>
    </body>

</html>

As you might expect, clipping operations can only be used in < input > or < textarea > elements.

Copy text from attributes

In fact, you don't even need another element to copy its content. You can include the data-clipboard-text attribute in your trigger element.

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>constructor-nodelist</title>
        <script src="https://cdn.jsdelivr.net/clipboard.js/1.6.0/clipboard.min.js"></script>
    </head>

    <body>
        <!-- Trigger -->
        <button class="btn" data-clipboard-text="Just because you can doesn't mean you should — clipboard.js">
            Copy to clipboard
        </button>
        <br/>
        <input type="" name="" id="" value="" placeholder="You can paste it here to see the effect."/>

        <!-- 3. Instantiate clipboard by passing a list of HTML elements -->
        <script>
            var btns = document.querySelectorAll('button');
            var clipboard = new Clipboard(btns);

            clipboard.on('success', function (e) {
                console.log(e);
            });

            clipboard.on('error', function (e) {
                console.log(e);
            });
        </script>
    </body>

</html>

Event

In some cases, you want to show some user feedback or capture the behavior after the selected copy/cut operation.
That's why we customize events such as successes and errors to allow you to monitor and execute your custom logic.

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>constructor-nodelist</title>
        <script src="https://cdn.jsdelivr.net/clipboard.js/1.6.0/clipboard.min.js"></script>
    </head>

    <body>
        <input id="foo" value="https://github.com/zenorocha/clipboard.js.git">

        <!-- Trigger -->
        <button class="btn" data-clipboard-target="#foo">
            Copy to clipboard
        </button>

        <p class="p1"></p>
        <p class="p2"></p>
        <p class="p3"></p>

        <script>
            var btns = document.querySelectorAll('button');
            var clipboard = new Clipboard('.btn');

            clipboard.on('success', function (e) {
                console.log(e)
                document
                    .querySelector('.p1')
                    .innerHTML = 'Action: ' + e.action;
                document
                    .querySelector('.p2')
                    .innerHTML = 'Text:  ' + e.text;
                document
                    .querySelector('.p3')
                    .innerHTML = 'Trigger:  ' + e.trigger;

                e.clearSelection();
            });

            clipboard.on('error', function (e) {
                document
                    .querySelector('.p1')
                    .innerHTML = 'Action: ' + e.action;
                document
                    .querySelector('.p3')
                    .innerHTML = 'Trigger:  ' + e.trigger;
            });
        </script>
    </body>

</html>

Live demonstration, just need to open the console.

Advanced Usage

If you don't want to modify HTML, there is a very convenient imperative API for you to use. All you need to do is declare a function, do your job, and return a value.
For example, if you want to set a goal dynamically, you need to return a node. (It seems that there is no support for the interface to appear at the same time as the console, so the operation can not see the print information and can be completely copied and run directly.)

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>constructor-nodelist</title>
        <script src="https://cdn.jsdelivr.net/clipboard.js/1.6.0/clipboard.min.js"></script>
    </head>

    <body>

        <!-- Target -->
        <input id="foo" value="https://github.com/zenorocha/clipboard.js.git">

        <!-- Trigger -->
        <button class="btn" data-clipboard-target="#foo">
            Copy to clipboard
        </button>

        <!-- 3. Instantiate clipboard by passing a list of HTML elements -->
        <script>
            var btns = document.querySelectorAll('button');
            var clipboard = new Clipboard(btns, {
                target: function (trigger) {
                    console.log(trigger.previousElementSibling);
                    return trigger.previousElementSibling;
                }
            });
        </script>
    </body>

</html>

If you want to set a text dynamically, you need to return a string. (Note that data-clipboard-target attributes can no longer be added to the target element, and errors will be reported)
There are two ways of writing:

Returns a fixed string directly

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>constructor-nodelist</title>
        <script src="https://cdn.jsdelivr.net/clipboard.js/1.6.0/clipboard.min.js"></script>
    </head>

    <body>
        <!-- Trigger -->
        <button class="btn">Copy to clipboard</button>

        <!-- 3. Instantiate clipboard by passing a list of HTML elements -->
        <script>
            var btns = document.querySelectorAll('button');
            var clipboard = new Clipboard('.btn', {
                text: function () {
                    return 'to be or not to be';
                }
            });
        </script>
    </body>

</html>

Get the return hidden in the attributes of the target element

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>constructor-nodelist</title>
        <script src="https://cdn.jsdelivr.net/clipboard.js/1.6.0/clipboard.min.js"></script>
    </head>

    <body>
        <!-- 1. Define some markup -->
        <button class="btn" aria-label='Define some markup'>Copy to clipboard</button>
        <br/>
        <input type="" name="" id="" value="" placeholder="You can paste it here to see the effect."/>

        <!-- 3. Instantiate clipboard -->
        <script>
            var clipboard = new Clipboard('.btn', {
                text: function (trigger) {
                    return trigger.getAttribute('aria-label');
                }
            });

            clipboard.on('success', function (e) {
                console.log(e);
            });

            clipboard.on('error', function (e) {
                console.log(e);
            });
        </script>
    </body>

</html>

Also, if you're using a single page application, you might want to manage life cycle DOM more accurately. It teaches you how to clean up the created events and objects.

var clipboard = new Clipboard('.btn');
clipboard.destroy();

Browser Compatibility

This library depends on Selection and execCommand APIs. The former is compatible with all browsers, while the latter is compatible with the following browsers.


The good news is, if you need to be compatible with the older version of clipboard.js, support elegant degradation. All you have to do is to pop up a prompt box for replication when the execution is successful, and press Ctrl + C to prompt the callback function for the failed event because the text has been selected.
You can also see if clipboard.js is supported by running Clipboard.isSupported(), so that you can hide the copy / cut button from the UI.

Here's what I said. This is an important step in the whole article and the reason why I dare to use it directly in the project. As we all know, plug-ins mostly have their own limitations and compatibility problems. It will take a lot of time and energy to toss those out. More often, because of the level problem, they can't start at all.
If I have a method to support it, I will let it appear. If I don't support it, I will let users copy it by themselves. There is no aftermath work!

Clipboard.isSupported()

Keywords: Javascript Attribute github git npm

Added by dumdumsareyum on Thu, 01 Aug 2019 06:08:16 +0300