Created
February 6, 2017 17:03
-
-
Save fhferreira/af2cd1056758c7a211ac9246a5769e9c to your computer and use it in GitHub Desktop.
Copy html to clipboard with Format
This file contains 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
function html2clipboard(html, el) { | |
var tmpEl; | |
if (typeof el !== "undefined") { | |
// you may want some specific styling for your content - then provide a custom DOM node with classes, inline styles or whatever you want | |
tmpEl = el; | |
} else { | |
// else we'll just create one | |
tmpEl = document.createElement("div"); | |
// since we remove the element immedeately we'd actually not have to style it - but IE 11 prompts us to confirm the clipboard interaction and until you click the confirm button, the element would show. so: still extra stuff for IE, as usual. | |
tmpEl.style.opacity = 0; | |
tmpEl.style.position = "absolute"; | |
tmpEl.style.pointerEvents = "none"; | |
tmpEl.style.zIndex = -1; | |
} | |
// fill it with your HTML | |
tmpEl.innerHTML = html; | |
// append the temporary node to the DOM | |
document.body.appendChild(tmpEl); | |
// select the newly added node | |
var range = document.createRange(); | |
range.selectNode(tmpEl); | |
window.getSelection().addRange(range); | |
// copy | |
document.execCommand("copy"); | |
// and remove the element immediately | |
document.body.removeChild(tmpEl); | |
} | |
document.getElementById("foo").addEventListener("click", function () { | |
html2clipboard("My <b>bold</b> text"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment