'How to format selected/copied html content without javascript?
In my particular case, I have a reusable component that displays a formatted weight (e.g. "12 kg 560 g").
The html that makes that up exists in DOM without any whitespace. But when formatted looks something like:
<span class="weight">
<span>12</span>
<span>kg</span>
<span>560</span>
<span>g</span>
</span>
That gets styled with CSS to add spacing to what's rendered. But when I copy that text from chrome and paste it as text, it comes out as "12kg560g".
I'm aware I can add whitespace to solve this particular issue, but what if I want an entirely alternate representation? For example: "12 KG. 560 G. (123.123 LBS.)".
The img tag has the alt attribute which browsers treat as the text representation. Why isn't this a global attribute? Is there any way (without using javascript) to help the browser format the selected elements when copied?
Edit: After reviewing the html spec and thinking on this, it's pretty safe to say it's not possible. Selecting arbitrary portions of a web page and copying/pasting as text just sucks
Solution 1:[1]
This should work, set the clipboard event data. More info: How to add extra info to copied web text
function changeContent(elem, content) {
elem.addEventListener("copy", evt => {
evt.clipboardData.setData("text/html", content(elem.innerHTML));
evt.preventDefault();
});
}
changeContent(document.querySelector("p"), content => `${content} foo bar 123 abcd <br> more multiline stuff <br> <h1> html yay </h1>`);
div {
border: 1px solid black;
}
<h1>Test copy content</h1>
<p>Lorem <u>ipsum</u> dolor sit <b>amet</b>, consectetur <i>adipiscing</i> elit.</p>
<h1>Try to paste here</h1>
<div contenteditable></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sean-7777 |
