0

I'm using contenteditable div as an editor and sometimes I add some code. I need to wrab that code inside code element.

to do that I made the next attempt.

Usage:

  1. add some text with line breaks.
  2. select that text.
  3. Click the button to wrap the selection.

The problem: when I wrap the selection it loses, unwantedly, all line breaks.

function wrapSelection(){
    var selected = window.getSelection().toString();
    if (selected != null) {
        document.execCommand('insertHTML', false, code(selected));
    };
}

var code = function (S) {
    var str = "<code>" + S + "</code>";
    return str;
};
#design_view {
    border: 1px solid gray;
    padding: 10px;
    min-height: 200px;
    font-size: 20px;
}
<button onClick="wrapSelection()">Select and Click</button>

<div contenteditable id="design_view">

</div>
MOHAMED ABUELATTA
  • 305
  • 2
  • 5
  • 15

1 Answers1

0

Add style='white-space: pre-wrap;' to your <code> element

code function would become:

    var code = function (S) {
        var str = "<code style='white-space: pre-wrap;'>" + S + "</code>";
        return str;
    };

See this answer for a more in depth explanation

BankBuilder
  • 466
  • 2
  • 10