Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  199] [ 2]  / answers: 1 / hits: 121196  / 7 Years ago, thu, july 13, 2017, 12:00:00

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!


More From » clipboard

 Answers
42

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>




[#57099] Tuesday, July 11, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mackennamelissac

Total Points: 110
Total Questions: 118
Total Answers: 103

Location: Sweden
Member since Sun, Jan 16, 2022
2 Years ago
;