简体   繁体   中英

JavaScript: copy text to clipboard and append source hyperlink

I do simple website dev with HTML, CSS, and WordPress. I can implement JavaScript, and trial-and-error with it just a little, but I'm not good with it, at all.

I have a client who wants the functionality of Tynt, but they want it activated when a button is clicked (on button click, text is copied to clipboard, and hyperlink appended). Basically, they want to make sharing their content as easy as possible, but they want to encourage attribution as well.

I've used the "Complex Example" found in the 2nd answer here , and simply added "+ document.location.href" to the end of the text copied. Everything works, but the link pastes as plain text, not as an active hyperlink.

I tried combining it with the top answer here , but couldn't figure out how to append the hyperlink to the copied text.

Here's what I have (note: this is just partial, take a look at the referenced questions if you'd like to see the complete code - I'm just trying to figure out how to append an active hyperlink to copied text).

var copyBtn = document.querySelector('.js-copy-btn'),

copyBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Text. Powered by: ' + document.location.href);
}); 

Clicking the HTML button with the class js-copy-btn and pasting produces this:

"Text. Powered by: http://websiteaddress.com "

However, the link pastes as plain text rather than as a hyperlink. How do I force the link to paste as a hyperlink rather than plain text?

I came across the same problem recently and solved it. I hope you have also solved it but still want to post the answer as I couldn't find any straight away solution to this.

 function CopyToClipboard(containerid) { if (document.selection) { var range = document.body.createTextRange(); range.moveToElementText(document.getElementById(containerid)); range.select().createTextRange(); document.execCommand("copy"); } else if (window.getSelection) { var range = document.createRange(); range.selectNode(document.getElementById(containerid)); window.getSelection().removeAllRanges(range); window.getSelection().addRange(range); document.execCommand("copy"); alert("text copied"); } } 
 <body> <div> <button id="button" onclick="CopyToClipboard('copyDiv')">Click to copy</button><br/> <div id="copyDiv"> <label>Text. Powered by: </label> <a href="http://websiteaddress.com">http://websiteaddress.com</a> </div> </div> </body> 

Put all the elements inside a div which you want to copy to clipboard( as is ) and call the function on button click or any other event along with the div id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM