timdown / rangy

A cross-browser JavaScript range and selection library.
MIT License
2.23k stars 367 forks source link

Put caret position at starting of inserted DIV #473

Open Myilvaganan opened 3 years ago

Myilvaganan commented 3 years ago

@timdown will clearly explain about my functionality needed.

I have a one contenteditable div element. If a user presses a Enter key, the the cotnents from the caret position to the end of the element, is extracted and inserted as separated node below of that DIV.

Also, need to get focus on inserted node element. But the caret is in-between the two DIVS.

Find my code below:

Here Range = rangy.getSelection(); RangeSel = Range.getRangeAt(0);

` const paraSplit = (Range, RangeSel) => { var clone_range = RangeSel.cloneRange(); var p = clone_range.commonAncestorContainer; while (p && p.nodeType !== 1) { p = p.parentNode; } if (p) { // Place the end of the range after the paragraph clone_range.setEndAfter(p);

// Extract the contents of the paragraph after the caret into a fragment
var contentAfterRangeStart = clone_range.extractContents();

// Collapse the range immediately after the paragraph
clone_range.collapseAfter(p);

// Insert the content
clone_range.insertNode(contentAfterRangeStart);

console.log(p.firstChild)
// Move the caret to the insertion point
clone_range.collapseAfter(p);
Range.setSingleRange(clone_range);
Range.setStart(RangeSel.startContainer, RangeSel.startOffset);
return true;

} }; `

This function gets triggered on keypressevent using Enter key.

`
const ParaSplitHandler = async (e) => { try { if (e.key === "Enter") { //Initializing range selections let Range = await rangy.getSelection(); let RangeSel = Range.getRangeAt(0); //ParaSplit on Enter event paraSplit(Range, RangeSel);

  }
} catch (error) {
  console.error(error);
}

}; <div id="main" ref={createId} onKeyPress={(e) => ParaSplitHandler(e)}> <div contentEditable="true"

loremEpsum jContrary to popular belief, Lorem Ipsum is not simply random text.It has roots in a piece of classical Latin literature from

    </div>

`