Skip to content

Instantly share code, notes, and snippets.

@JamesMGreene
Last active November 5, 2019 07:47
Show Gist options
  • Save JamesMGreene/8589353 to your computer and use it in GitHub Desktop.
Save JamesMGreene/8589353 to your computer and use it in GitHub Desktop.
HTML Clipboard API clarification example
var btn = document.getElementById("copy-button");
btn.addEventListener("click", clickHandler, false);
btn.addEventListener("copy", copyHandler, false);
function clickHandler(e) {
e.target.dispatchEvent(new ClipboardEvent("copy"));
}
function copyHandler(e) {
e.clipboardData.setData("text/plain", "Simulated copy. Yay!");
// CRITICAL: Must call `preventDefault();` to get this data into the system/desktop clipboard!!!
e.preventDefault();
}
@med5
Copy link

med5 commented Nov 15, 2014

Hello James,
thank you for your Html clipboard example, actually I'm looking for a html5 code to copy a html code like this one:

<div id="copytext" class="highlight">
<pre><code class="language-html" data-lang="html"><span class="nt">&lt;div</span>
<span class="nt">&lt;/div&gt;</span></code></pre>
</div>

<div class="btn-group btn-group-sm">
<button id="btn1" class="btn btn-default" title="copy me" onclick="f1();">Copy</button>
</div>

my idea is to make a button, so when I click on it, this code will be copied to the clipboard and then I can copy it anywhere in Notepad for example. just for a remarque this code is in my html body.

I have tried your example but it is only working if I copy a text not a html code.

I would very grateful if you can help to resolve this specially that I'm still new in HTML5 domain.

Best regards.

@philipjc
Copy link

Hi, I am getting an uncaught type error: illegal constructor error when I try and use ClipboardEvent.

@cgatian
Copy link

cgatian commented Feb 12, 2016

@kresli
Copy link

kresli commented Nov 23, 2016

You are not allowed to create constructor on ClipboardEvent in any browser but FF. Please refer to http://caniuse.com/#feat=clipboard

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment