Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy text string on click

I spent a good 20 min searching online for this, but couldn't find it. What I want is to to be able to copy a text string on click without a button. The text string will be inside a "span" class.

  1. User hovers over text string
  2. User clicks text string
  3. Text string is copied to clipboard

Any help would be greatly appreciated. Thanks!

like image 479
Matthew Avatar asked Jul 13 '17 04:07

Matthew


People also ask

How do you copy text with mouse click?

Copy can also be performed by clicking the mouse's middle button (i.e., the scroll wheel button) while pressing the Ctrl key if option Middle Mouse Button Paste is enabled.

How do I copy text from a Div button click?

Just add the clipboard. js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.


2 Answers

You can attach copy event to <span> element, use document.execCommand("copy") within event handler, set event.clipboardData to span .textContent with .setData() method of event.clipboardData

const span = document.querySelector("span");    span.onclick = function() {    document.execCommand("copy");  }    span.addEventListener("copy", function(event) {    event.preventDefault();    if (event.clipboardData) {      event.clipboardData.setData("text/plain", span.textContent);      console.log(event.clipboardData.getData("text"))    }  });
<span>text</span>
like image 52
guest271314 Avatar answered Oct 01 '22 00:10

guest271314


Try this .document.execCommand('copy')

  1. click the element and copy the text and post with tmp input element
  2. Then copy the text from this input

function copy(that){  var inp =document.createElement('input');  document.body.appendChild(inp)  inp.value =that.textContent  inp.select();  document.execCommand('copy',false);  inp.remove();  }
<p onclick="copy(this)">hello man</p>
like image 43
prasanth Avatar answered Oct 01 '22 02:10

prasanth