Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Put caret position at starting of inserted DIV #473

Open
Myilvaganan opened this issue Jul 12, 2021 · 0 comments
Open

Put caret position at starting of inserted DIV #473

Myilvaganan opened this issue Jul 12, 2021 · 0 comments

Comments

@Myilvaganan
Copy link

Myilvaganan commented Jul 12, 2021

@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);
}

};

ParaSplitHandler(e)}>
loremEpsum jContrary to popular belief, Lorem Ipsum is not simply random text.It has roots in a piece of classical Latin literature from
    </div>
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant