Copy to Clipboard - JS

by Lio Fleishman

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<!-- Copy to clipboard -->
<label for="error">Error:</label>
<input type="text" id="error" value="Failed To Find Country ID:126115853 and Country Name:AUSTRALIA in the GIS Countries Table" />
<button data-copytarget="#error" class="fa fa-copy"></button>

<label for="warning">Warning:</label>
<input type="text" id="warning" value="The latitude and longitude are 0 in destination, destination key: 198811648. In W6MultiProviderGISServices::QueryRoute" />
<button data-copytarget="#warning" class="fa fa-copy"></button>

SCSS

body {
  font-family: sans-serif;
  font-size: 1em;
  color: #333;
  background-color: #ddd;
}

label {
  clear: both;
  display: block;
  font-size: 0.85em;
  font-weight: bold;
  padding: 0.8em 0 0.2em 0;
  user-select: none;
}

input,
button {
  float: left;
  font-size: 1em;
  padding: 10px 6px;
  margin: 0;
  border: 1px solid #333;
  outline: 0;
  box-shadow: none;
}

::-moz-focus-inner {
  padding: 0;
  border: 0;
}

input {
  width: 15em;
  background-color: #fff;
  border-radius: 3px;
	&:hover {
		background-color: #ccc;
	}
}

button {
    position: relative;
    background-color: #fff;
    border-radius: 50%;
    cursor: pointer;
    padding: 12px;
    height: 42px;
    left: 8px;
    top: -1px;
    -webkit-filter: drop-shadow(2px 2px 3px rgba(121,121,121,0.9));
		transition: all .5s;
}

.copied{
	&:after {
		position: absolute;
		top: 13%;
		right: 110%;
		display: block;
		content: "copied";
		font-size: 0.75em;
		font-family: helvetica neue;
		padding: 2px 3px;
		color: #fff;
		background-color: #2ecc71;
		border-radius: 3px;
		opacity: 0;
		will-change: opacity, transform;
		animation: showcopied 1.5s ease;
	}
}

@keyframes showcopied {
  0% {
    opacity: 0;
    transform: translateX(100%);
  }
  70% {
    opacity: 1;
    transform: translateX(0);
  }
  100% {
    opacity: 0;
  }
}

JavaScript

/*
Copy to clipboard
*/

(function() {

  'use strict';

  // click events
  document.body.addEventListener('click', copy, true);

  // event handler
  function copy(e) {

    // find target element
    var
      t = e.target,
      c = t.dataset.copytarget,
      inp = (c ? document.querySelector(c) : null);

    // is element selectable?
    if (inp && inp.select) {

      // select text
      inp.select();

      try {
        // copy text
        document.execCommand('copy');
        inp.blur();

        // copied animation
        t.classList.add('copied');
        setTimeout(function() {
          t.classList.remove('copied');
        }, 1500);
      } catch (err) {
        alert('please press Ctrl/Cmd+C to copy');
      }

    }

  }

})();