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 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 line 1, the CSS class .copy is the class that will work as an indicator. You have to add this class for the clicked 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 you add code in the head or body “Simple Custom CSS and JS“.

Leave a Reply

Your email address will not be published. Required fields are marked *