0

I know there other similar examples out there surrounding this question. But none quite like this.

I am attempting to copy the input's value to the user's clipboard with JS and jQuery using execCommand but suspect I am misusing it. Any direction would be much appreciated.

Here is my html:

<div class="2 columns">
    <div class="js swatch container">
        <div class="js swatch color chartreuse"></div>
        <div class="swatch information">
            <span class="swatch title">Chartreuse</span>
            <input class="js swatch data" type="text" value="#31bc06" readonly>
        </div>
    </div>
</div>

And here is my JS:

// .js.swatch.container
var swatchContainer = $('.js.swatch.container');
var swatchData = $('.js.swatch.data');
swatchContainer.mouseenter(function() {
    $(this).children().children(swatchData).select();
});
swatchContainer.mouseleave(function() {
    $(this).children().children(swatchData).blur();
});
// test
swatchContainer.click(function() {
    $(this).children().children(swatchData).execCommand('copy');
});

Thanks in advance.

DanMad
  • 1,245
  • 3
  • 15
  • 45
  • Do look here https://developers.google.com/web/updates/2015/04/cut-and-copy-commands – Stuart Jan 19 '17 at 13:39
  • I think you need to `select()` first as in http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript – GôTô Jan 19 '17 at 13:42
  • Possible duplicate of [How do I copy to the clipboard in JavaScript?](http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – GôTô Jan 19 '17 at 13:42

1 Answers1

1

You need to select text to temporary location and than call .execCommand('copy'). I have this code that works for me:

$(document).on('click', '.js.swatch.container', function () {
    var $temp = $("<textarea>");
    $("body").append($temp);
    $temp.val($(this).text()).select();
    var coppied = document.execCommand("copy");
    $temp.remove();
});
Justinas
  • 34,232
  • 3
  • 56
  • 78