Open In App

How to Set Cursor Position in Content-Editable Element using JavaScript?

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
11 Likes
Like
Report

To set the cursor position in content-editable elements, such as a div tag, you can use the JavaScript Range interface. A range is created using the document.createRange() method.

Approach:

  • First, create a Range and set the position using the above syntax.
  • Get user input from the input tag using jQuery
    $("input']").val();
    
  • On the button click assign input value to range function to return cursor position on div.

Syntax:

// document.createRange() creates new range object
letrangeobj = document.createRange();

// Here 'rangeobj' is created Range Object
letselectobj = window.getSelection();

// Here 'selectobj' is created object for window
// get selected or caret current position.
// Setting start position of a Range
rangeobj.setStart(startNode, startOffset);

// Setting End position of a Range
rangeobj.setEnd(endNode, endOffset);

// Collapses the Range to one of its
// boundary points
rangeobj.collapse(true);

// Removes all ranges from the selection
// except Anchor Node and Focus Node
selectobj.removeAllRanges();

// Adds a Range to a Selection
selectobj.addRange(rangeobj);

Example 1: Below example illustrate how to set caret cursor position on content-editable element div based on user input.

Output:

output

Example 2: Below example illustrates how to set caret cursor position on content-editable element div.

Output:

output

Next Article

Similar Reads