-1

I have three span with same class

<div>
    <span class="textValue">Atul</span>
    <span class="textValue">Kumar</span>
    <span class="textValue">Rajput</span>
</div>

I just want that, If I click on any of the spans, then the value of that span will be copied to the clipboard.

i.e. if I click on first span then "Atul" will be copied into the clipboard.

Liam
  • 27,717
  • 28
  • 128
  • 190
Atul Rajput
  • 4,073
  • 2
  • 12
  • 24
  • 2
    https://www.w3schools.com/howto/howto_js_copy_clipboard.asp – Mehdi Jul 13 '18 at 12:39
  • 2
    Have you even tried to tackle this on your own? https://www.w3schools.com/howto/howto_js_copy_clipboard.asp If yes post the code you wrote so we can fix it. – DanteTheSmith Jul 13 '18 at 12:40
  • 2
    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) – Liam Jul 13 '18 at 12:41

3 Answers3

1

You can not select a span so you have to create a temporary textarea with the textContent of the span to execute the copy command.

<div>
    <span class="textValue" onClick="copy(this)">Atul</span>
    <span class="textValue" onClick="copy(this)">Kumar</span>
    <span class="textValue" onClick="copy(this)">Rajput</span>
</div>
<p/>
Try to paste the text that you copied:
<br/>
<input type="text"/>
 <p/>
<span id="result"></span>
<script>
var result = document.getElementById("result");
function copy(el){
  var copyText = el.textContent;
    var textArea = document.createElement("textarea");
    textArea.value =  copyText;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand("Copy");
   textArea.remove();
   result.innerHTML = "Copied text: "+copyText;
}
</script>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

You can try this

 $(".textValue").click(function () {
    var spanVal = $(this).text();
    document.execCommand("copy");
    alert(spanVal);
});
  • 1
    jQuery's `live()` method was removed in jQuery version 1.9. You should use `on()` instead. Also, your method does not work. – Unmitigated Jul 13 '18 at 18:39
-2

You can try this codepen for different layout

OR

This Codepen

this way

const span = document.querySelector("span");
var result = document.getElementById("result");
function copy(el){
  var copyText = el.textContent;
    var textArea = document.createElement("textarea");
    textArea.value =  copyText;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand("Copy");
   textArea.remove();
   result.innerHTML = "Copied text: "+copyText;
}
</script>
<div>
    <span class="textValue"  onClick="copy(this)">Atul</span>
    <span class="textValue"  onClick="copy(this)">Kumar</span>
    <span class="textValue"  onClick="copy(this)">Rajput</span>
</div>

<span id="result"></span>
Ankit Jaiswal
  • 274
  • 2
  • 8