1

I have several li tags with different background colors. and I want to when user click on each of li tags, get the background color of that specific item and copy it to clipboard.

 $('li.col').click(function () {
    var x = $(this).css('backgroundColor');
})

How can I do this?

  • Not an answer, but something to consider. You may be more suitable to use [clipboard.js](https://github.com/zenorocha/clipboard.js) – David Picksley Sep 13 '18 at 15:43

1 Answers1

0

Your approach is correct so far. You can use something like the copyToClipboard method from 30secondsofcode (a project/website that I maintain) to deal with this. From the website:

Create a new <textarea> element, fill it with the supplied data and add it to the HTML document. Use Selection.getRangeAt() to store the selected range (if any). Use document.execCommand('copy') to copy to the clipboard. Remove the <textarea> element from the HTML document. Finally, use Selection().addRange() to recover the original selected range (if any).

const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
};


$('li.col').click(function() {
  var x = $(this).css('backgroundColor');
  copyToClipboard(x);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="col" style="background:red;">Red</li>
  <li class="col" style="background:green;">Green</li>
  <li class="col" style="background:blue;">Blue</li>
</ul>

Note: I've written an article on Medium that explains this technique a bit more in depth. You can read it here.

Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75