Wednesday, July 3, 2024
HomeLanguagesJavascriptHow to set cursor position in content-editable element using JavaScript ?

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

In order to set caret cursor position in content editable elements like div tag is carried over by JavaScript Range interface. The range is created using document.createRange() method.

Approach 1:

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

Following syntax explain clearly:

Syntax:

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

// Here 'rangeobj' is created Range Object
var selectobj = 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.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1">
  
    <script src=
    </script>
      
    <style>
        div {
            outline-color: red;
            caret-color: red;
            color: #ddd;
            width: 550px;
            text-align: justify;
            border: 2px solid red;
        }
    </style>
</head>
  
<body>
    <center>
        <h1 style="color:green;padding:13px;">
            GeeksforGeeeks
        </h1>
        <br>
          
        <div id="editable" contenteditable="true"
                    spellcheck="false">
            HTML stands for Hyper Text Markup Language.
            It is used to design web pages using markup 
            language. HTML is the combination of Hypertext
            and Markup language. Hypertext defines the link 
            between the web pages. Markup language is used 
            to define the text document within tag which 
            defines the structure of web pages. HTML is a 
            markup language which is used by the browser
            to manipulate text, images and other content 
            to display it in required format.
        </div>
        <br/>
          
        <input type="number" name="position" min="0"
                value="0" max="470" />
          
        <button>Position Cursor</button>
    </center>
  
    <script>
        function setCursor(pos) {
            var tag = document.getElementById("editable");
              
            // Creates range object
            var setpos = document.createRange();
              
            // Creates object for selection
            var set = window.getSelection();
              
            // Set start position of range
            setpos.setStart(tag.childNodes[0], pos);
              
            // Collapse range within its boundary points
            // Returns boolean
            setpos.collapse(true);
              
            // Remove all ranges set
            set.removeAllRanges();
              
            // Add range with respect to range object.
            set.addRange(setpos);
              
            // Set cursor on focus
            tag.focus();
        }
      
        $('button').click(function() {
            var $pos = $("input[name='position']").val();
            setCursor($pos);
        });
    </script>
</body>
  
</html>


Output:

  • Before Entering the position:
  • After Entering the position:

Approach 2:

  • First create Range and set position using above syntax.
  • On button click trigger function to return cursor position on div.

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




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1">
          
    <script src=
    </script>
      
    <style>
        div {
            outline-color: red;
            caret-color: red;
            color: #ddd;
            width: 550px;
            text-align: justify;
            border: 2px solid red;
        }
    </style>
</head>
  
<body>
    <center>
        <h1 style="color:green;padding:13px;">
            GeeksforGeeeks
        </h1>
        <br>
  
        <div id="editable" contenteditable="true"
                    spellcheck="false">
            HTML stands for Hyper Text Markup Language.
            It is used to design web pages using markup
            language. HTML is the combination of Hypertext
            and Markup language. Hypertext defines the
            link between the web pages. Markup language
            is used to define the text document within
            tag which defines the structure of web pages. 
            HTML is a markup language which is used by
            the browser to manipulate text, images and
            other content to display it in required
            format.
        </div>
        <br/>
          
        <button>Position Cursor</button>
    </center>
      
    <script>
        function positionCursor() {
              
            var tag = document.getElementById("editable");
              
            // Creates range object
            var setpos = document.createRange();
              
            // Creates object for selection
            var set = window.getSelection();
              
            // Set start position of range
            setpos.setStart(tag.childNodes[0], 12);
              
            // Collapse range within its boundary points
            // Returns boolean
            setpos.collapse(true);
              
            // Remove all ranges set
            set.removeAllRanges();
              
            // Add range with respect to range object.
            set.addRange(setpos);
              
            // Set cursor on focus
            tag.focus();
        }
      
        $('button').click(function() {
            positionCursor();
        });
    </script>
</body>
  
</html>


Output:

  • Before Clicking the Button:
  • After Clicking the Button:

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Range

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments