Reputation: 87
<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
Reputation: 752
Try html() instead of text()
$temp.val($(element).html()).select();
Upvotes: 0
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
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