Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On click - copy to clipboard

Tags:

<p id="p1"> 
...here is a lot of text (html) mixed with php...
</p>
<button onclick="copyToClipboard('#p1')">Copy to clipboard</button>
------
JS

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

When I click on the button, results are copied but without bold, underline, rows and other formatting things. How can I copy it as it is displayed by default?

like image 846
FabianCannes Avatar asked Aug 10 '17 14:08

FabianCannes


People also ask

How do I click copy to clipboard?

Copy and paste multiple items using the Office Clipboard Open the file that you want to copy items from. Select the first item that you want to copy, and press CTRL+C.

Where is clipboard button?

To get to your clipboard history at any time, press Windows logo key + V. From the clipboard history, you can paste and pin frequently used items by choosing an individual item from your clipboard menu.


1 Answers

Assuming all your styles are inline, you need to get the html of the element rather than the text. Something like:

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).html()).select(); //Note the use of html() rather than text()
  document.execCommand("copy");
  $temp.remove();
}

Edit based on comments:

To copy formatting to something like a Gmail message body or a Word document you have to actually select the element as a range. When you insert the html content into a textarea you are actually copying the raw text. You want to do something like this:

function copyToClipboard(element) { //Note, element should be a node rather than a jQuery instance.
    var selection = window.getSelection(), //Get the window selection
        selectData = document.createRange(); //Create a range

        selection.removeAllRanges();  //Clear any currently selected text.
        selectData.selectNodeContents(element); //Add the desired element to the range you want to select.
        selection.addRange(selectData); //Highlight the element (this is the same as dragging your cursor over an element)
        var copyResult = document.execCommand("copy");  //Execute the copy.

        if(copyResult) //was the copy successful?
            selection.removeAllRanges(); //Clear the highlight.
        else
            alert("Your browser does not support clipboard commands, press ctrl+c");
}
like image 72
TheGentleman Avatar answered Sep 22 '22 20:09

TheGentleman