Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
DEV

Copy text in Javascript

Copy text in Javascript

To copy the text in javascript we can use execCommand(“copy”). This command copies the selected text. Check latest magento 2 extensions.

To copy the text in javascript we can use execCommand(“copy”). This command copies the selected text.

Here is an example that I used to copy the browser URL.

<input type="button" onclick="copyOnClick()" value="Copy" />
function copyOnClick() {  
    var tempInput = document.createElement("input");
    tempInput.style = "position: absolute; left: -1000px; top: -1000px";
    tempInput.value = window.location.href;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand("copy");
    document.body.removeChild(tempInput);
    alert("Link copied");
}

Now on button click, the javascript function copyOnClick() will execute because copyOnClick() is written in the ‘onclick’ event.

As you can see in the code a temporary input field has the browser URL as its value. With the select() command the text value of the temporary input field is selected and the execCommand(“copy”) copies it.

At last, remove the temporary created input.

Happy coding 🙂

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • Zaz
    • Paul Dutta (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home