Clint
Clint

Reputation: 179

How to preserve white space in a textnode?

I am intercepting a paste event and cleaning any html off of it using textNodes.

It works great, other than the fact that it reduces all whitespace to a single space, and disregards new lines completely. For example if a user were to paste

"hello world

!"

then it would paste as "hello world !"

How can I keep the white space and new lines? Any javascript, jquery, or css tricks would be great. Here is my code:

iframe.contentWindow.focus()
var sel, range;
if (iframe.contentWindow.getSelection) {
    sel = iframe.contentWindow.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
        range = sel.getRangeAt(0);
        range.deleteContents();}
text = window.clipboardData.getData("Text");
frag = iframe.contentDocument.createTextNode(text);
range.insertNode(frag);

Upvotes: 1

Views: 1858

Answers (1)

Stack Underflow
Stack Underflow

Reputation: 2453

I had the same problem and was able to solve it with nnnnnn's suggestion in the comments above.

.range_class{
    white-space: pre;
}

Where .range_class is the css class of the element the text node is being inserted into.

Upvotes: 2

Related Questions