Clipboard.js: How can I use this to copy img tag

Created on 6 Jan 2017  路  3Comments  路  Source: zenorocha/clipboard.js

I use it like this
but I got the src not the image

`


<!-- 2. Include library -->
<script src="../dist/clipboard.min.js"></script>

<!-- 3. Instantiate clipboard -->
<script>
var clipboard = new Clipboard('.btn');

clipboard.on('success', function(e) {
    console.log(e);
});

clipboard.on('error', function(e) {
    console.log(e);
});
</script>`

Most helpful comment

Clipboard.js is only intended for copying text.

All 3 comments

I use when setting up a CDN, <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.13/clipboard.min.js"></script>
And I don't understand what you mean? You want to copy a image? or save the image? Not sure if it's possible.

But -doesn't mean you can't try:

You apparently are new - so you are missing a vital step which is a button - I use link buttons (easier to style xD )

but you need to set the following:
data-clipboard-action="copy" data-clipboard-target="img"

You need the Js you have as well to make it work.

Update: Looks like currently only text can be copied.

So to copy a image. Try this:
JS/Jquery:
//Cross-browser function to select content function SelectText(element) { var doc = document; if (doc.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); } } $(".copyable").click(function (e) { //Make the container Div contenteditable $(this).attr("contenteditable", true); //Select the image SelectText($(this).get(0)); //Execute copy Command //Note: This will ONLY work directly inside a click listenner document.execCommand('copy'); //Unselect the content window.getSelection().removeAllRanges(); //Make the container Div uneditable again $(this).removeAttr("contenteditable"); //Success!! alert("image copied!"); });
And the HTML

<div class="copyable"><img src="image.jpg" alt="Copy Image to Clipboard via Javascript."/></div>

Can't guarantee it will work the code is older (found on Stack)

This works at least in Safari/Chrome:

<div>
    <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350脳150&w=350&h=150" alt="">
</div>
<button data-clipboard-action="copy" data-clipboard-target="div">Copy</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.13/clipboard.min.js"></script>
<script>new Clipboard('button');</script>

Demo on JSFiddle

Clipboard.js is only intended for copying text.

Was this page helpful?
0 / 5 - 0 ratings