Click to copy content by javascript

  • Home
  • Click to copy content by javascript
Click to copy content by javascript

Sometimes we need to add a function to copy content automatically.
Suppose you want to copy a big content or code by clicking a “Click to copy” or something like this indicator.

Here is the solution.
Please follow the steps as shown below.

Step 01: link this by pasting in the HTML head tag.

<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>

Step 02: Paste this JavaScript before closing </body> tag.

<script>
var btns = document.querySelectorAll('.copy');
var clipboard = new ClipboardJS(btns);
clipboard.on('success', function (e) {
console.log(e);
});
clipboard.on('error', function (e) {
console.log(e);
});
</script>

In the line 1, the CSS class .copy is the class that will work as indicator. You have to add this class for click element.

Now your website is ready to copy content anywhere.

<span class="copy" data-clipboard-target="#content">©</span>
<pre id="content">Text need to copy</pre>

Here the “ data-clipboard-target ” this is the showing the CSS ID name. It will find this ID in this case CSS ID is “content”

Note: this plugin can help yo add code in the head or body “Simple Custom CSS and JS“.

Leave a Reply

Your email address will not be published.