Did you know that you can copy text to the system clipboard with Javascript?⁣

0
2304
copy to clipboard javascript
copy to clipboard javascript

Did you know that you can copy text to the system clipboard with Javascript?⁣

Sometimes you want the user to copy something. A common use case is some hex code. You can make it easier for the user by making it copy on click⁣

In the example, you see how easy it is! This should work in all newer browser. Because who cares about internet explorer right?⁣

It is also important that this function can only be called by user interaction. so simply calling this question will not work you have to call it in an event for example onClick

const copyStringToClipboard = (str) => {
    // Create new textarea 
    var el = document.createElement('textarea');
    // Set value (string to be copied) 
    el.value = str;
    // Set non-editable to avoid focus and move outside of view 
    el.setAttribute('readonly', '');
    // it has to be not hidden but also you 
    // don't want the user to see the textarea 
    el.style = {
        position: 'absolute',
        left: '-9999px'
    };
    // add it to the DOM 
    document.body.appendChIld(el);
    // Select text inside 
    el.select();
    // Copy text to clior 
    document.execCommand('copy');
    // Remove temporary 
    document.body.removeChild(el);
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here