How to set cursor position on contentEditable div with JavaScript?

To set the cursor position within a contentEditable <div> element using JavaScript, you can utilize the Selection object.

For example, we write:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Cursor Position in contentEditable DIV</title>
</head>
<body>

<div id="editableDiv" contenteditable="true">This is a contentEditable div. Click here to edit.</div>

<script>
    // Function to set cursor position
    function setCursorPosition(element, position) {
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(element.childNodes[0], position);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        element.focus();
    }

    // Usage: Set cursor position to the end
    var editableDiv = document.getElementById('editableDiv');
    setCursorPosition(editableDiv, editableDiv.textContent.length);
</script>

</body>
</html>

In this example, we define a function setCursorPosition(element, position) that takes an HTML element (contentEditable div in this case) and a position as arguments.

Inside the function, we create a Range object and a Selection object.

Then, we set the start of the range to the specified position within the child node of the element (assuming it’s a text node).

Next we collapse the range to the specified position.

We remove all existing ranges from the selection and add the newly created range.

Finally, we focus on the contentEditable element to make the cursor appear at the specified position.

In the usage part, we call this function with the contentEditable div element and the length of its text content to set the cursor position to the end. You can adjust the position as needed.