Last active
May 25, 2018 05:25
-
-
Save saineshmamgain/78f3a99b709de16111d5e9b2cb9dfc0e to your computer and use it in GitHub Desktop.
copy html contents to clipboard using javascript
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> | |
<!-- | |
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>[email protected]</td> | |
</tr> | |
<tr> | |
<td>John Doe</td> | |
<td>[email protected]</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