All documentation ↓← All docs

editor.collapse(bStart)

Collapses the current selection down to a single insertion point (a caret with no highlighted text). Use it after a programmatic selection or a command that acted on a range, when you want to place the caret at one edge of what was selected rather than leave the whole range highlighted.

Syntax

editor.collapse(bStart)

Parameters

bStart — boolean. true collapses the selection to its start, false to its end. Omitting it behaves like false (collapse to the end).

Returns

Nothing (undefined).

Behavior notes

  • Already-collapsed selections are left alone. If the selection is already a caret, collapse() returns immediately without moving it.
  • No active range selects the document first. If there is no selection range at all (for example the editor has not been focused yet), collapse() falls back to selecting the whole document, so the call still leaves a well-defined selection to work from.
  • It operates on the live selection,the same one the user sees — there is no separate caret to keep in sync.

Example usage

Apply a command to the whole document, then drop the caret at the end so typing continues after it:

Code example
var editor1 = new RichTextEditor("#div_editor1");
editor1.setHTMLCode("<b>hello world</b>");
editor1.selectDoc();
editor1.execCommand("forecolor", "red");
editor1.collapse(false);   // caret lands after the colored text

Collapse to the start instead, to position the caret before the selection:

Code example
editor1.selectDoc();
editor1.collapse(true);    // caret lands at the very beginning

Related

Calling editor.collapse() from your app

editor.collapse() belongs to the editor instance. Every integration below works the same way: keep the object that new RichTextEditor(...) returns, and call it on that object.

Plain JavaScript

Code example
var editor1 = new RichTextEditor("#div_editor1");
// The constructor is synchronous: the editor is ready on the next line.
editor1.collapse(bStart);

React and Next.js

Code example
// editorRef is filled by the RichTextEditor wrapper from the React guides.
const editorRef = useRef(null);

function onClick() {
  editorRef.current?.collapse(bStart);
}

return <RichTextEditor editorRef={editorRef} />;

In Vue and Angular, the wrapper components in the guides keep the instance in a component variable (editor), so the call is the same. See the React, Vue and Angular pages, or download a tested project from the guides.

If the editor is undefined

  • The call ran before the component mounted. Call it from an event handler or after the mount effect has run.
  • In React development mode, Strict Mode mounts, unmounts and mounts again, so the wrapper sets editorRef.current to null in between. Use editorRef.current?. rather than storing the instance elsewhere.
  • The editor was destroyed (editor.destroy()) when its component unmounted.

All methods: method reference · all events: event reference.