Semytech
Semytech

Reputation: 773

Replace last character while user typing in contenteditable div

I found, somewhere in SE, a code to insert text in contenteditable by Tim Down. The code looks like the following and is working perfect. But I want to add a condition that is based on my requirement and wanted to modify the code somehow but failed to do it after so many trials.

function insertTextAtCursor(value, stepback) {
    var sel, range, textNode;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);         
            textNode = document.createTextNode(value);


           //Check value of stepback: 0 or 1
            if(!stepback)//if 0
                 range.insertNode(textNode);
            if(stepback){ //if 1
               // replace the previously inserted character with the new one here

            }

            // Move caret to the end of the newly inserted text node   
            range.setStart(textNode, textNode.length);
            range.setEnd(textNode, textNode.length);

            sel.removeAllRanges();
            sel.addRange(range);          

        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.pasteHTML(text);
    }
}

Here I am checking the value of the stepback parameter which is 0 or 1. If 0 then the pressed character will be inserted but if 1 I want to replace the last character with the new one. In my case, the stepback returns 1 when a key is pressed immediately followed by a vowel (for instance, pressing m followed by a). How can I modify the code to achieve this condition? Spent days to figure out this but to no avail.

Thanks.

Upvotes: 2

Views: 1860

Answers (1)

Chandranshu
Chandranshu

Reputation: 3669

In place of the following:

//Check value of stepback: 0 or 1
if(!stepback)//if 0
     range.insertNode(textNode);
if(stepback){ //if 1
   // replace the previously inserted character with the new one here

}

use the following code:

// This clones the selected range and then selects 1
// 1 character in the backward direction and deletes it.
if(stepback){
    clone = range.cloneRange();
    clone.setStart(range.startContainer, range.startOffset - 1);
    clone.setEnd(range.startContainer, range.startOffset);
    clone.deleteContents();
}
range.insertNode(textNode);

This ensures that the new translated character is always added at the end while optionally removing the 1 character in case stepback is required.

UPDATE: I have tested this in Chromium only.

Upvotes: 4

Related Questions