FabianCannes
FabianCannes

Reputation: 87

On click - copy to clipboard

<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?

Upvotes: 5

Views: 5334

Answers (3)

Ivan Bolnikh
Ivan Bolnikh

Reputation: 752

Try html() instead of text()

$temp.val($(element).html()).select();

Upvotes: 0

TheGentleman
TheGentleman

Reputation: 2352

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");
}

Upvotes: 3

Sergej
Sergej

Reputation: 2176

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).html()).select();
  document.execCommand("copy");
  $temp.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="p1"> 
...here is a lot of <b>text</b> (html) mixed with php...
</p>
<button onclick="copyToClipboard('#p1')">Copy to clipboard</button>

Upvotes: 1

Related Questions