I want to create a button that when I click it, text is copied to my desktop clipboard. I want this button to be on the customer's order page, the same place where the customer's order details are listed. The idea is to create some buttons that will allow me to copy some different, predetermined texts. With customer service with emails with customers, does anyone have any idea what file to write it to?
Here you have a JS function. This will copy any parameter passed to the first let variable. You can modify it the way you like:
function copyToClipboard() {
let textToCopy = "I want to get copied into my clipboard",
urlInput = document.createElement( "input" );
document.body.appendChild( urlInput );
urlInput.setAttribute( "value", textToCopy );
if ( navigator.userAgent.match( /ipad|ipod|iphone/i ) ) {
let contentEditable = urlInput.contentEditable,
readOnly = urlInput.readOnly,
range = document.createRange(),
windowSelection = window.getSelection();
urlInput.contentEditable = !0;
urlInput.readOnly = !1;
range.selectNodeContents( urlInput );
windowSelection.removeAllRanges();
windowSelection.addRange( range );
urlInput.setSelectionRange( 0, 999999 );
urlInput.contentEditable = contentEditable;
urlInput.readOnly = readOnly
} else urlInput.select();
document.execCommand( "copy" );
document.body.removeChild( urlInput );
alert( "Successfully copied to clipboard" );
}
You can call it via a button vor example:
<button onclick="copyToClipboard()">Copy to clipboard</button>
Also, you can pass a parameter to the function:
<button onclick="copyToClipboard('I want to get copied into my clipboard')">Copy to clipboard</button>
In this case you need to modify the top of your JS function this way:
function copyToClipboard(textToCopy) {
You also need to remove the re-definition of the variable textToCopy
. Otherwise it would override your value passed to your function.