Skip to content

Instantly share code, notes, and snippets.

@ruzicic
Created March 16, 2017 08:04
Show Gist options
  • Save ruzicic/fe9a44b485c33f733c796bed1f0df34e to your computer and use it in GitHub Desktop.
Save ruzicic/fe9a44b485c33f733c796bed1f0df34e to your computer and use it in GitHub Desktop.
Copy input value to clipboard
const copy = e => {
// find target
const clickTarget = e.target;
const hasCopytarget = clickTarget.dataset.copytarget;
const inputVal = hasCopytarget ? document.querySelector(hasCopytarget) : null;
// Is element selectable?
if (inputVal && inputVal.select) {
// select text
inputVal.select();
try {
// copy text
document.execCommand('copy');
inputVal.blur();
// copied notification animation
clickTarget.classList.add('copied');
setTimeout(() => clickTarget.classList.remove('copied'), 1500);
} catch (err) {
alert('Please press CTRL/CMD+C to copy');
}
}
};
document.body.addEventListener('click', copy, true);
.copied::after {
position: absolute;
top: 12%;
right: 110%;
display: block;
content: "copied";
font-size: 0.75em;
padding: 2px 3px;
color: #fff;
background-color: #22a;
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;
}
}
<!-- Note: Bootstrap classes used; Remove if not using bootstrap -->
<div class="input-group">
<input id="myInputField" type="text" placeholder="Some value">
<span class="input-group-btn">
<button
class="btn btn-secondary"
type="button"
data-copytarget="#myInputField">Copy to clipboard</button>
</span>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment