Home > Mobile >  How to create copy to clipboard icon without input filed?
How to create copy to clipboard icon without input filed?

Time:10-28

I have this Vue.js code:

      <div class="border">
        <h4>{{ name }}</h4>
        <div class="code">
          <p>{{ code }}</p>
          <img src="~/assets/img/copy.svg" alt="" @click="copy"/>
        </div>
      </div>

There is copy function on copy button. What I want is to copy code field in clipboard. I was looking for a solution on the internet, but there were solutions only for input filed, but, as you can see, I have just paragraph.

I was trying to use ref and id on that paragraph, but it doesn't work. With ref:

<p ref='code'>{{ code }}</p>
copy() {
  this.$refs.code.focus()
  document.execCommand('copy')
}

With id:

<p id='code'>{{ code }}</p>
copy(id) {
  const input = document.querySelector(`#${id}`)
  input.setAttribute('type', 'text')
  input.select()
  document.execCommand('copy')
  input.setAttribute('type', 'hidden')
}

CodePudding user response:

Try this

Html

   <p id="text_element">Copy this !</p>
   <button onclick="copyToClipboard('text_element')">
   Copy to clipboard
   </button>

Javascript

function copyToClipboard(elementId) {
var aux = document.createElement("input");
aux.setAttribute("value", document.getElementById(elementId).innerHTML);
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
document.body.removeChild(aux);}
function log() {
console.log('---')
}
  • Related