menu

Questions & Answers

How to create copy button using html and javascript?

Hii am new to javascript but by putting my all efforts I have written a javascript to copy text inside a <p></p> elements. In my website I need the copy button many times. But my javascript work for only one copy button. if I used it to another copy button it would copy the first button's respective <p>/p> text. My javascript

const copyButton = document.querySelector('.copyButton');
const copyalert = document.querySelector('.copyalert');

copyButton.addEventListener('click', copyClipboard);

function copyClipboard() {
  var copystatus= document.getElementById("randomstatus");
// for Internet Explorer

  if(document.body.createTextRange) {
    var range = document.body.createTextRange();
    range.moveToElementText(copystatus);
    range.select();
    document.execCommand("Copy");
    window.getSelection().removeAllRanges();
    copyalert.classList.add("show");
    setTimeout(function() {copyalert.classList.remove("show")},700);
  }
  else if(window.getSelection) {
// other browsers

    var selection = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(copystatus);
    selection.removeAllRanges();
    selection.addRange(range);
    document.execCommand("Copy");
    window.getSelection().removeAllRanges();
    copyalert.classList.add("show");
    setTimeout(function() {copyalert.classList.remove("show")},700);
  }
}

My html

<div>
   <h2 class="statusheading">Latest English quotes</h2>
  <div id="englishquotes">
   <div class="latestquotes">
       <p class=latest>life os good when hou have books</p>
       <button class="copyButton btn">Copy</button>
          <span class="copyalert">Copied!</span>
</div>
<div class="latestquotes">
       <p class=latest>Google is a open source library</p>
       <button class="copyButton btn">Copy</button>
          <span class="copyalert">Copied!</span>
   </div>
<div class="latestquotes">
       <p class=latest>Cat is better than dog</p>
       <button class="copyButton btn">Copy</button>
          <span class="copyalert">Copied!</span>
   </div>
  </div>
  </div>

Comments:
2023-01-21 23:10:02
A different approach: navigator.clipboard.writeText(newClipText) NOTE: check browser compatibility
Answers(4) :

You don't have to rely on execCommand. Nowadays there is the Clipboard API. All modern browser support it.

The Clipboard API provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the system clipboard.

Demo of a copy button:

const copy = async() => {
  return await navigator.clipboard.writeText(document.querySelector("#source").value);
}

document.querySelector("#copy").onclick = copy
<textarea id="source"></textarea>
<button id="copy">copier</button>

You just need to let the system knows the id of the text you want to copy , e.g. p1, p2, p3.

Please try this

<div>
   <h2 class="statusheading">Latest English quotes</h2>
  <div id="englishquotes">
   <div class="latestquotes">

       <p><div id=p1>life os good when hou have books</div></p> 
       <button class="copyButton btn" onclick="copyToClipboard('p1')">Copy</button>

</div>

 

<div class="latestquotes">

       <p><div id=p2>Google is a open source library</div></p>
       <button class="copyButton btn" onclick="copyToClipboard('p2')">Copy</button>

   </div>

 

<div class="latestquotes">

       <p><div id=p3>Cat is better than dog</div></p>
       <button class="copyButton btn" onclick="copyToClipboard('p3')">Copy</button>

   </div>
  </div>
  </div>


<script>


function copyToClipboard(var1){
    let val = document.getElementById(var1).innerHTML;
    const selBox = document.createElement('textarea');
    selBox.style.position = 'fixed';
    selBox.style.left = '0';
    selBox.style.top = '0';
    selBox.style.opacity = '0';
    selBox.value = val;
    document.body.appendChild(selBox);
    selBox.focus();
    selBox.select();
    document.execCommand('copy');
    document.body.removeChild(selBox);
    alert('text copied to clipboard, please use Ctrl-V to paste the data');

  }  


</script>
Comments:
2023-01-21 23:10:02
Can you make it possible without jQuery? Please
2023-01-21 23:10:02
No problem. I have already revised my answer - not using jquery. Please try again.
2023-01-21 23:10:02
works for me, I had to change .innerHTML to value for element with input tag

You have to create a text area, append to body and apply execCommand function, then you can remove the textarea from your DOM, try this:

function copyToClipboard(){
    let val = 'text to copy';
    const selBox = document.createElement('textarea');
    selBox.style.position = 'fixed';
    selBox.style.left = '0';
    selBox.style.top = '0';
    selBox.style.opacity = '0';
    selBox.value = val;
    document.body.appendChild(selBox);
    selBox.focus();
    selBox.select();
    document.execCommand('copy');
    document.body.removeChild(selBox);
    alert('text copied to clipboard');
  }
<button type=button onclick="copyToClipboard()">Copy</button>

Comments:
2023-01-21 23:10:03
No, it doesn't work. it copies "text to copy" word if I click any button.
2023-01-21 23:10:03
you can pass an argument to function copyToClipboard(argument){let val = argument}
2023-01-21 23:10:03
Although I got answer, but I can't understand your code.
2023-01-21 23:10:03
If you will to understand more about it, it's quite similar to the code shown here from Dean Taylor.

This is the code you need, replace the ID names with the ones you need. With this, you can assign the specific behavior you need to each button independently by changing the ID names for which you need and the relationship (button ---> paragraph tag) between them.

HTML:

const copyButton = document.getElementById("copy-button");
const outputText = document.getElementById("output-text");

Javascript:

const copyButton = document.getElementById("copy-button");
const textToCopy = document.getElementById("output-text");

copyButton.addEventListener("click", () => {
 textToCopy.select();
 document.execCommand("copy");
});

Another way to do this is using the Clipboard API just like this

Javascript:

copyButton.addEventListener("click", () => {
  navigator.clipboard.writeText(outputText.value)
  .then(() => {
    copyButton.textContent = "Copied!";
    setTimeout(() => {
      copyButton.textContent = "Copy";
    }, 2000);
  })
  .catch(err => {
    console.error("Error writing to clipboard: ", err);
  });
});

The difference between these two methods is that the clipboard API is a relatively new feature that allows web developers to interact with the clipboard directly from JavaScript. This means that you can read from and write to the clipboard without the need for a user to manually copy or paste the text.

When you use the clipboard API, you can create a button that automatically copies text to the clipboard when clicked, which provides a better user experience. The user does not need to manually select and copy the text, the button does it for them.

On the other hand, if you don't use the clipboard API, you would need to use a different approach, such as creating a temporary input field, selecting the text, and then using the document.execCommand('copy') method to copy the text to the clipboard. This approach is considered as less user-friendly, since it requires the user to manually select the text, and can also be less reliable.

It's worth noting that the clipboard API is not supported by all browsers, so you might need to use a polyfill or fallback to a different approach for older browsers.