0

HTML

<input type="text" id="clipboard">
<button class="share-button">share</button>

JS

  text = 'text to be copied';

  document.querySelector('.share-button').addEventListener('click', () => {
      var element = document.querySelector('#clipboard');
      element.setAttribute("value", text);
      console.log(element.value);
      element.select();
      document.execCommand('copy');

  });

CSS

#clipboard {
  position: absolute;
  visibility: hidden;
}

I am trying to copy text to the clipboard but I don't understand what wrong with my code. I copied the code from MDN documentation.

When I doing these things it is not working

#clipboard {
  position: absolute;
}

// or

#clipboard {
  visibility: hidden
}

// or

#clipboard {
  display: none
}
  • Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Adam Azad Aug 04 '20 at 07:02
  • could you share your html? or create a https://jsfiddle.net/ for full source – Mammad2c Aug 04 '20 at 07:03

1 Answers1

1

const share_btn = document.querySelector('.share-button');

function copy_to_clipboard(stritem){
    const el = document.createElement('textarea');
    el.value = stritem;
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    window.alert('Successfully copied to your clipboard!'); 
}

text = 'text to be copied';
share_btn.addEventListener('click', ()=>{copy_to_clipboard(text);});
<button class="share-button">share</button>
Weilory
  • 1,194
  • 4
  • 15