Request Quote

Copy text in Javascript

Copy text in Javascript

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

Here is an example that I used to copy 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()  written in onclick event.

As you can see the code that a temporary input field has the browser url as its value. With select() command the text value of the temporary input field is selected and the execCommand(“copy”) copies it. At last remove the tempoary created input.

 

Happy coding 🙂

 

. . .

Comments (2)

Add Your Comment

  • Zaz
    Your article title is “copy text in javascript”. You should not use jQuery in your code 🙂
    • Paul Dutta
      code updated
  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close