Skip to content

Instantly share code, notes, and snippets.

@wuliupo
Created October 13, 2016 02:57
Show Gist options
  • Save wuliupo/180061aec2d779fb0f24eeef99200a7a to your computer and use it in GitHub Desktop.
Save wuliupo/180061aec2d779fb0f24eeef99200a7a to your computer and use it in GitHub Desktop.
Pure JavaScript Copy
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Copy</title>
</head>
<body>
<h1>Pure JavaScript Copy</h1>
<button id="copyBtn">Copy Content</button>
<button id="randomBtn">Change Content</button>
<hr/>
<textarea id="contentArea" cols="50" rows="5"></textarea>
<script>
(function() {
'use strict';
var copyBtn = document.getElementById('copyBtn'),
randomBtn = document.getElementById('randomBtn'),
contentArea = document.getElementById('contentArea');
copyBtn.addEventListener('click', function() {
if (contentArea.select) {
contentArea.select();
} else {
let range = document.createRange();
range.selectNode(contentArea);
window.getSelection().addRange(range);
}
try {
document.execCommand('copy');
contentArea.blur();
}
catch (err) {
alert('please press Ctrl/Cmd+C to copy');
}
}, true);
randomBtn.addEventListener('click', function() {
contentArea.value = Math.random() * 100000000;
}, true);
randomBtn.click();
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment