JSFiddle - React, Tailwind, and code Playground

by Aubrey Taylor

HTML

<p class="to-copy">Chuck ipsum. Although it is not common knowledge, there are actually three sides to the Force: the light side, the dark side, and Chuck Norris.</p>
<button class="copy-btn" type="button">Copy!</button>
<br />
<br />
<div>
    <div>
        <label for="paste">Paste!</label>
    </div>
    <textarea name="paste" id="paste" cols="30" rows="10"></textarea>
</div>

JavaScript

var $toCopy = $('.to-copy')
var $copyBtn = $('.copy-btn');

$copyBtn.on('click', function (e) {
    var target = $toCopy[0];
    var range = document.createRange();
    var selection = window.getSelection();
    var selectedText;

    selection.removeAllRanges();
    range.selectNodeContents(target);
    selection.addRange(range);
    selectedText = selection.toString();

    console.log(selectedText);

    try {
        if (!document.execCommand('copy')) {
            alert('copy did not succeed');
        }
    } catch (e) {
		alert('this browser does not support this feature');
    }
});