Netskin Logo

Copy to Clipboard with Javascript

by Tom Rothe on 31.05.2022

Recently, we wanted to implement a little share button. When the user clicks it, the relevant link is added to the clipboard. This should not be too hard.

I rummaged through some of my old code and found the following snippet:

function copyToClipboard(contents) {
  var textArea = document.createElement("textarea");
  textArea.value = contents;"fixed";  // avoid scrolling to bottom
  try {
    alert(document.execCommand('copy') ? 'Successfully copied.' : 'could not copy :('); }
  catch (err) {
    alert('could not copy because ' + err);

Wow, this did not look like the 21st century. A quick search on showed that this code is supported by 96% of the “internet users”. But there had to be a smoother way.

There is also the Navigator.clipboard API, which still has 91.6% of support. This should be ok for such a non-essential feature. Here an example:

function copyToClipboard(contents) {
  if (typeof(navigator.clipboard) == 'undefined') { return; }

      _ => alert('Successfully copied!'),
      _ => alert('could not copy :(')

This looks much nicer and the user does not see any textareas flashing.

Happy Coding!


❮ Retrieve Provider's Job-Id from Delayed-Job Adapter
Test ActiveJob Retry Logic in RSpec ❯
Netskin Logo