JavaScript Copy to Clipboard Button

JavaScript Copy to Clipboard Button
Code Snippet: Copy execCommand
Author: Michael Richins
Published: January 17, 2024
Last Updated: January 22, 2024
Downloads: 6,291
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create copy to clipboard button. It uses Document.execCommand() feature to run copy command to save the text to the clipboard.

The plugin comes with an interactive copy button that handle basics errors and also alert the users if their browser doesn’t support copy to clipboard functionality. Besides this, users are also notified with “copied” text when they successfully copied the text to the clipboard.

You can integrate this copy button with paragraphs, textarea, and other HTML elements that contains text to allow users to save a specific text to the clipboard.

How to Create JavaScript Copy to Clipboard Button

1. First of all, create p element or textarea with “data-copy-text” attribute and place your text inside it.

 <div class="container">
  <div class="wrap">
    <div class="box">
      <p data-copy-text="">Say goodbye to these, because it's the last time! I hear the jury's still out on science. I've opened a door here that I regret. I'm a monster. Really? Did nothing cancel? I'm afraid I just blue myself.</p>
    </div>
    <div class="box">
      <p data-copy-text="">I don't criticize you! And if you're worried about criticism, sometimes a diet is the best defense. I don't criticize you! And if you're worried about criticism, sometimes a diet is the best defense. Say goodbye to these, because it's the last time!</p>
    </div>
  </div>
</div>

2. After that, add the following CSS styles for copy to clipboard button. You can also define your own styles if needed.

:root {
  font-size: 16px;
}
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  line-height: 1;
  border: 0;
}
html,
body {
  width: 100vw;
  min-width: 100vw;
  height: 100vh;
  min-height: 100vh;
}
body {
  background-color: #f5f5f4;
  font-family: 'Catamaran', sans-serif;
}
p {
  font-size: 1.25rem;
  line-height: 1.25;
}
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
.container .wrap {
  flex: 0 1 37.5rem;
  margin: 0.625rem;
}
.container .wrap .box {
  padding: 1.25rem;
  background-color: #fff;
  border: 0.0625rem solid #607d8b;
  border-radius: 0.1875rem;
}
.container .wrap .box:not(:last-child) {
  margin-bottom: 1.5625rem;
}
[data-copy-text] + i.material-icons {
  transition: all 0.25s ease-in-out;
  position: absolute;
  top: 0;
  right: 0;
  background-color: #f5f5f4;
  padding: 0.3125rem 0.625rem;
  color: #000;
  border-color: #607d8b;
  border-style: solid;
  border-top-right-radius: 0.1875rem;
  border-bottom-width: 0.0625rem;
  border-left-width: 0.0625rem;
  opacity: 0.3;
  cursor: pointer;
  z-index: 1;
}
[data-copy-text] + i.material-icons:hover,
[data-copy-text] + i.material-icons.active {
  background-color: #607d8b;
  opacity: 1;
  color: #fff;
}

3. Finally, add the following JavaScript code and done.

'use strict';

document.addEventListener('DOMContentLoaded', function() {
	copyText.init()
});

var copyText = {
	init: function() {
		if (document.querySelectorAll('[data-copy-text]').length) {
			var cp = document.querySelectorAll('[data-copy-text]');

			for (var i = 0, l = cp.length; i < l; i++) {
				copyText.addCopy(cp[i]);
			}
		}
	},
	addCopy: function(el) {
		if (typeof el !== 'undifined') {
			var parent = el.parentNode;
			if (!parent.querySelectorAll('span.copy-btn').length && window.getSelection) {
				var cpBtn = document.createElement('I');

				parent.setAttribute('style', 'position:relative');
				parent.appendChild(cpBtn);

				cpBtn.classList.add('material-icons');
				cpBtn.textContent = 'content_copy';
				cpBtn.setAttribute('title', 'Copy Text');

				copyText.addCopyEvent(cpBtn, el);
			}
		}
	},
	addCopyEvent: function(btn, el) {
		var coppied = false;
		var timer = 0;

		function copyText() {
			function showCheckmark() {
				btn.textContent = 'check';
				btn.classList.add('active');
			}

			function hideCheckmark() {
				btn.classList.remove('active');
				btn.textContent = 'content_copy';
				timer = 0;
			}
			
			if (timer === 0) {
				if (window.getSelection) {
					var selection = window.getSelection();
					var range = document.createRange();
					range.selectNodeContents(el);
					selection.removeAllRanges();
					selection.addRange(range);

					try {
						document.execCommand('copy');
						coppied = true;
					} catch (err) {
						console.error(err);
					}

					selection.removeAllRanges();
				} else {
					console.error('your browser does not support copy');
				}

				if (coppied) {
					clearTimeout(timer);
					showCheckmark();
					timer = setTimeout(hideCheckmark, 2000);
				}
			}
		}

		if (typeof btn !== 'undifined' && typeof el !== 'undifined') {
			btn.addEventListener('click', copyText, false);
		}
	},
}

That’s all! hopefully, you have successfully integrated this copy to clipboard code snippet into your project. If you have any questions or facing any issues, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X