Skip to content

Instantly share code, notes, and snippets.

@8lall0
Last active June 21, 2018 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 8lall0/10ecb9c31981d31b9abfe2f4a8d2b0e0 to your computer and use it in GitHub Desktop.
Save 8lall0/10ecb9c31981d31b9abfe2f4a8d2b0e0 to your computer and use it in GitHub Desktop.
How to copy the content of a span on click in javascript (no jQuery)
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.copyInput {
border: none;
overflow: auto;
outline: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
width: 0px;
height: 0px;
position: absolute;
opacity: 0;
}
#thaSpan {
cursor: pointer;
}
</style>
</head>
<body>
<span id="thaSpan">The brown lazy fox</span>
<script>
bindCopy('thaSpan');
function bindCopy(spanSelector, callback) {
let span = document.getElementById(spanSelector);
span.addEventListener('click', copySpan, false);
function copySpan() {
let input = document.createElement('textarea');
input.readOnly = true;
input.className += ' copyInput';
document.body.appendChild(input);
input.value = span.innerHTML;
input.select();
document.execCommand("Copy");
setTimeout(function() {
input.selectionEnd = input.selectionStart;
input.blur();
input.parentNode.removeChild(input);
if (typeof callback === 'function') callback();
}, 1);
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment