Open In App

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

Last Updated : 28 Nov, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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



Similar Reads

How to place cursor position at end of text in text input field using JavaScript ?
In this article, we are going to learn about how to place the cursor at the end of the text in a text input element using JavaScript.  At first, we are going to create a text input box where some value will be given and a button to place the cursor at the end. We can place the cursor at the end of the text in a text input element by using different
2 min read
How to insert text into the textarea at the current cursor position?
To insert text into the textarea/inputbox at the current cursor position we need to get the current position of the cursor. So here the approach to get the current position of the cursor. First, get the current position of cursor with the help of property named as selectionStart on textarea/inputbox.To insert the text at the given position we will
2 min read
Content editable change event in jQuery
In General, jQuery provides various function to handle selectors, selector properties and even documents, etc. Whereas here using jquery change event for content editable. jQuery Change Event: It occurs when the value of an element is changed also this event is fired immediately when the user makes a selection with the mouse or when the field loses
3 min read
How to make your content editable in HTML ?
The contenteditable attribute is used to specify whether the element's content is editable by the user or not. It uses the boolean values true or false. If the attribute is given without a value, like &lt;h1 contenteditable&gt;GEEKSFORGEEKS&lt;/h1&gt;, its value is treated as an empty string and the empty string will be treated as true. This attrib
2 min read
How to remove border from an editable element using CSS ?
Given an HTML document containing some document and the task is to remove border from an editable element using CSS. It is a default behavior of any element which have content-editable attributes set to true whenever, the element gets a focus it will get a border around them. The task can be done by using the [attribute] selector to select all elem
1 min read
How to set the cursor to wait in JavaScript ?
In JavaScript, we could easily set the cursor to wait. In this article, we will see how we are going to do this. Actually, it's quite an easy task, there is a CSS cursor property and it has some values and one of the values is wait. We will use the [cursor: wait] property of CSS and control its behavior using JavaScript. Setting the cursor to the w
3 min read
Hide the cursor in a webpage using CSS and JavaScript
In this article, we are going to learn how to Hide the cursor on a webpage using CSS and JavaScript. ApproachFirst, select the element where the cursor element needs to hide.Add CSS style cursor: none to the class.Add the class name (class name of CSS style cursor: none) to the particular element where the cursor element is to be hidden.Example 1:
2 min read
How to create editable div using JavaScript ?
In this article, we will be explaining to you how to create an editable div using HTML, CSS, and JavaScript. An editable div is one on which is you will click then it will generate an editable text area to edit or to write any text on your browser itself. After editing, when you click on somewhere else on your browser then that text will be display
3 min read
How to set cursor style that indicates any direction scroll using CSS ?
In this article, we will see how to set the cursor style for any direction using CSS. This style can be created by using all-scroll cursor property. This property sets the cursor that it indicates any direction scroll using CSS. The all-scroll property value indicates that something can be scrolled in any direction. Syntax: cursor: all-scroll; Exam
1 min read
How to set the cursor style on browser using CSS ?
The cursor property in CSS is used to specify the type of mouse cursor to be displayed when pointing over an element. By default, all the browser's cursor is set to the pointer. And if we want to customize it, we can do it with the help of CSS. By default, the value of the cursor property is set to 'auto'. Also, mentioning the value auto to the cur
1 min read