0

I recently built a very simple tool to randomly generate colors and gradients. I would like to add a button that copies the CSS of the generated color/gradient. I have a variable created that generates the CSS color, so how can I set a function to copy that generated value to the clipboard?

Here is the basic HTML:

<section>
     <div id="card">
          <div id="generated-color"></div>
          <h1 id="color-text"></h1>
     </div>
     <button onclick="random_color()">Generate</button>
</section>

Here is the JS function:

function random_color() {
     var color = 'rgb(' + [Math.floor(Math.random() * 256)] + ',' + [Math.floor(Math.random() * 256)] + ',' + [Math.floor(Math.random() * 256)] + ')';
     document.getElementById('generated-color').style.background = color;
     document.getElementById("color-text").innerHTML = color;
}

So basically, how could I go about copying the "color" variable that is generated?

Here is a live demo of the site: https://color.lukecjohnson.com

mx0
  • 6,445
  • 12
  • 49
  • 54
Luke Johnson
  • 183
  • 2
  • 12
  • Did you try searching for an answer to this question? https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript – Joss Classey Apr 12 '18 at 19:45
  • 3
    Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Idan Apr 12 '18 at 19:45

2 Answers2

0

The best way to do this is to create an "invisible" textbox, focus it, and then trigger a clipboard copy event with execCommand.

function copyRandom(rand){
  let input = document.createElement("input");

  input.style.opacity="0";
  input.style["pointer-events"] = "none";
  document.body.appendChild(input);
  input.value = rand;
  input.focus();
  input.select();
  document.execCommand('copy');
  alert('copied!')
}

So...

function random_color(){
  ...
  copyRandom(color);
}

Or you could use a Flash solution.

yaakov
  • 4,568
  • 4
  • 27
  • 51
0

You can copy text directly from tag to clipboard like this:

document.getElementById('generate').addEventListener('click', function () {
  var text = document.getElementById('color-text').innerText;

  function listener(e) {
    e.clipboardData.setData('text/plain', text);
    e.preventDefault();
  }

  document.addEventListener('copy', listener);
  document.execCommand('copy');
  document.removeEventListener('copy', listener);
});
mx0
  • 6,445
  • 12
  • 49
  • 54