Created
October 13, 2016 02:57
-
-
Save wuliupo/180061aec2d779fb0f24eeef99200a7a to your computer and use it in GitHub Desktop.
Pure JavaScript Copy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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