How to set cursor position in content-editable element using JavaScript?


In HTML, content editable div allows users to edit the content of the div element. We need to pass the contenteditable attribute with true Boolean value to the div element to make any div element editable.

The content editable div contains the caret cursor by default, and sometimes we may require to set the caret cursor position in the content editable div element to edit the content of the div. However, we can set the caret cursor position anywhere by clicking at a particular place in the content editable div.

This tutorial will teach us to use different examples to set the caret cursor at a custom position.

Syntax

Users can follow the syntax below to set the caret cursor at a custom position in the content editable div.

var selectedText = window.getSelection();
var selectedRange = document.createRange();
selectedRange.setStart(text_div.childNodes[0], 45);
selectedRange.collapse(true);
selectedText.removeAllRanges();
selectedText.addRange(selectedRange);
text_div.focus(); 

In the above syntax, we have created a range and added it to the selected text, and after that, to show the cursor, we have focused on the content editable div.

Steps

Users can follow the below steps to set the caret cursor at a custom position in the content editable div.

Step 1 − First, get the content editable div using id, name, tag, etc.

Step 2 − After that, use the getSelection() method of the window object to select the text from the window.

Step 3 − Next, we need to create a range using the createRange() method.

Step 4 − Use the setStart() method of the range object, and set the starting position of the cursor by passing the value as a parameter.

Step 5 − Next, use the collapse method and pass the true Boolean value as a parameter to collapse all ranges at the boundaries of the div element.

Step 6 − After that, use the removeAllRange() method to remove all previous ranges from the text.

Step 7 − Now, we need to use the addRanges() method to add range to the selected text after removing ranges.

Step 8 − Use the focus method to set focus on the content editable div element.

Example

In the example below, we have created the div and added some texts in the div element. Also, we have added the contenteditable attribute to the div element to make it editable.

After that, we used the above algorithm to set the caret cursor at a custom position. In the output, users can observe that it sets the cusor at the 45th position in the content editable div when they refresh the web page.

<html>
<body>
   <h2>Setting up the <i> custom cursor position </i> in the content editable div</h2> <br>
   <div id = "text_div" contenteditable = "true" spellcheck = "false" style = "caret-color:red">
      This is a text of the content editable div. Users can click anywhere to place the cursor position. The cursor color is red. The initial cursor position is 45.
   </div>
   <script>

      // select content editable div element
      var text_div = document.getElementById("text_div");

      // select text from a window
      var selectedText = window.getSelection();
 
      // create a range
      var selectedRange = document.createRange();

      // set starting position of the cursor in the texts
      selectedRange.setStart(text_div.childNodes[0], 45);

      // collapse the range at boundaries
      selectedRange.collapse(true);

      // remove all ranges
      selectedText.removeAllRanges();

      // add a new range to the selected text
      selectedText.addRange(selectedRange);

      // focus the cursor
      text_div.focus();
   </script>
</body>
</html>

Example

In the example below, we have created the range input that takes the user's cursor position. After that, when the user clicks the button, the below code takes the input value and invokes the setCusorPosition() function by passing the input value as a parameter.

In the setCusorPosition() function, we have written the code to set the cursor at a custom position according to the algorithm explained. Also, we have used the try-catch block to catch the errors.

In the output, users can observe that setting a large value as input shows an error message.

<html>
<body>
   <h2>Setting up the <i> custom cursor position </i> in the content editable div</h2><br>
   <div id="editable_div" contenteditable="true" spellcheck="false" style="caret-color:blue">
      TutorialsPoint is the best platform to learn programming languages such as JavaScript, TypeScript, HTML, CSS, ReactJS, Java, Python, C, C++, etc.  TutorialsPoint also provides the best courses to learn particular programming languages from different tutors.  Students can choose their favourite tutor's course and learn concepts related to computer science with full fun.
   </div> <br />
   <input type = "number" id = "cursor_range" min = "0" value = "0" max = "500" /> <br> <br>
   <div id = "output"> </div>
   <button id = "button"> Set cursor position </button>
   <script>
      let output = document.getElementById('output');
      function setCursorPosition(customPosition) {
         try {
            evar element = document.getElementById("editable_div");
            evar selected = window.getSelection();
            evar range = document.createRange();
            erange.setStart(element.childNodes[0], customPosition);
            erange.collapse(true);
            eselected.removeAllRanges();
            eselected.addRange(range); 
            element.focus();
            output.innerHTML = "";
         } catch (error) {
            output.innerHTML = "The error is " + error.message;
         }
      }
      let btn = document.getElementById('button');
      btn.addEventListener('click', () => {
         let value = document.getElementById('cursor_range').value;
         setCursorPosition(value)
      })
   </script>
</body>
</html>

Users learned to set cursor position in the content editable div using JavaScript. In the first example, we have set the cursor at the 45th position, and in the second example, we have taken the custom position from the users.

Updated on: 22-Feb-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements