Copy Specified Text To Clipboard On Click

Category: Javascript , Text | August 28, 2018
Author:Adam Quinlan
Views Total:357 views
Official Page:Go to website
Last Update:August 28, 2018
License:MIT

Preview:

Copy Specified Text To Clipboard On Click

Description:

A copy-to-clipboard helper function that enables the user to copy the specified text to their clipboard with callback support.

How to use it:

Create an element to copy the text to your clipboard once clicked.

<button id="example">Clip To Clipboard</button>

The main copy to clipboard helper function.

let createCopy = function(textToCopy, triggerElementId, callback = null) {
  //add event listner to elementtrigger
  let trigger = document.getElementById(triggerElementId);
  trigger.addEventListener("click", function() {
    //create the readonly textarea with the text in it and hide it
    let tarea = document.createElement("textarea");
    tarea.setAttribute("id", triggerElementId + "-copyarea");
    tarea.setAttribute("readonly", "readonly");
    tarea.setAttribute(
      "style",
      "opacity: 0; position: absolute; z-index: -1; top: 0; left: -9999px;"
    );
    tarea.appendChild(document.createTextNode(textToCopy));
    document.body.appendChild(tarea);
    //select and copy the text in the readonly text area
    tarea.select();
    document.execCommand("copy");
    //remove the element from the DOM
    document.body.removeChild(tarea);
    //fire callback function if provided
    if (typeof callback === "function" && callback()) {
      callback();
    }
  });
};

Enable the button to copy the text ‘CSSSCRIPT.COM’ to your clipboard.

createCopy('CSSSCRIPT.COM', 'example', function () {
  alert('Copied!');
});

You Might Be Interested In:


Leave a Reply