Search code examples
javascriptvue.jscopyclickicons

How to apply copy function on a icon javascript?


[![enter image description here][1]][1]

strong text**

I have a copy icon in a website. I want to copy the website URL when I click the icon. the traditional method is working on input text but I failed to apply it on an icon.

            <div class="icon-container" style="display: inline-block;">
            <input class="paste" type="button" value="Copy Url" @click="urlCopy" id="copy" hidden/>
             <textarea class="paste" id="url" rows="1" cols="30" hidden></textarea>
            <img  style="display: inline-block" src="share.png" alt="">
        </div>


urlCopy() {
  console.log("sulg", this.slug.fullPath)
  let Url = document.getElementById("url");
  Url.innerHTML = window.location.href;
  console.log(Url.innerHTML)
  Url.select();
  document.execCommand("copy");

}

Solution

  • I strongly recommend to use vue-clipboard2. It will make copy url much easier than traditional method.

    Example

      <div id="app"></div>
     
      <template id="t">
        <div class="container">
        <input type="text" v-model="message">
        <button type="button" @click="doCopy">Copy!</button>
        </div>
      </template>
     
      <script>
      new Vue({
        el: '#app',
        template: '#t',
        data: function () {
          return {
            message: 'Copy These Text'
          }
        },
        methods: {
          doCopy: function () {
            this.$copyText(this.message).then(function (e) {
              alert('Copied')
              console.log(e)
            }, function (e) {
              alert('Can not copy')
              console.log(e)
            })
          }
        }
      })
      </script>