1

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.

3

1 Answer 1

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();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.