DanMad
DanMad

Reputation: 1735

Copy to clipboard with click JS

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.

Upvotes: 1

Views: 701

Answers (1)

Justinas
Justinas

Reputation: 43441

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();
});

Upvotes: 1

Related Questions