Skip to content

Instantly share code, notes, and snippets.

@saineshmamgain
Last active May 25, 2018 05:25
Show Gist options
  • Save saineshmamgain/78f3a99b709de16111d5e9b2cb9dfc0e to your computer and use it in GitHub Desktop.
Save saineshmamgain/78f3a99b709de16111d5e9b2cb9dfc0e to your computer and use it in GitHub Desktop.
copy html contents to clipboard using javascript
<!DOCTYPE html>
<!--
Created using multiple answers from StackOverFlow. Will only support modern browsers.
StackOverFlow answers:
http://stackoverflow.com/a/30566157/4485147
http://stackoverflow.com/a/2044793/4485147
-->
<html>
<head>
<title>Copy Html To ClipBoard</title>
</head>
<body>
<div id='copyTarget'>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sainesh Mamgain</td>
<td>mygmail@gmail.com</td>
</tr>
<tr>
<td>John Doe</td>
<td>johndoe@gmail.com</td>
</tr>
</tbody>
</table>
</div>
<button type='button' id='copyButton'></button>
</body>
</html>
<script>
document.getElementById("copyButton").addEventListener("click", function() {
selectElementContents(document.getElementById("copyTarget"));
});
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
}
document.execCommand('copy');
}
document.getElementById('copyTarget').addEventListener('copy', function (e) {
var html_data = document.getElementById('copyTarget').innerHTML;
e.clipboardData.setData('text/html', html_data);
e.preventDefault();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment