0

I have a div with contenteditable=true and a button for changing text div selected text onclick.

Div editable:

<div class="content" id="articleEditor" contenteditable="true"></div>

Style Options

<div class="editor-option">
    <button id="changeText">change</button>
</div>

Js file

function replaceSelectedText(replacementText){
    if (window.getSelection().rangeCount) {
        range = window.getSelection().getRangeAt(0);
        range.deleteContents();
        var el = document.createElement("span");
        el.innerHTML = replacementText;
        var frag = document.createDocumentFragment(), node, lastNode;
        while ( (node = el.firstChild) ) {
            lastNode = frag.appendChild(node);
        }
        range.insertNode(document.createTextNode(replacementText));
    }
}

$('button').click(function(){
    replaceSelectedText('<span class="bold">'+window.getSelection().toString()+'</span>');
})

Now it works for all text selection except the last word. If I select the last word and then I click on the button, the selection is bold but everything I write after is bold too.

How to fix this ?

Amadou Beye
  • 2,538
  • 3
  • 16
  • 37

1 Answers1

0

You might want to take a look at this: How to set caret(cursor) position in contenteditable element (div)?

I would try adding a space character to the replacement text and then setting the cursor after the end of that space.

(Also: note typo in your code, no close single-quote in the button-click function.)

Blunt Jackson
  • 616
  • 4
  • 17