How to Move the Caret or Cursor to Specific Coordinates Using JavaScript
![](/nks.jpg)
Nitish Kumar Singh
Feb 2, 2024Hello developers, in this blog post, we will learn how to move the cursor or caret (blinking line in text editing) to specific coordinates using JavaScript.
This function is useful in applications where we need to dynamically position cursor, such as text editors, note-taking apps, or any page allowing users to edit on-page content.
To achieve this, we will use the caretPositionFromPoint(x, y)
or caretRangeFromPoint(x, y)
function of the document
, depending on its availability in the Browser. This will allow us to obtain a Range object for the given coordinates. We'll then utilize the Selection API to move or position the cursor at those coordinates.
const moveCursorTo = (x,y)=> {
let range = document.caretPositionFromPoint ? document.caretPositionFromPoint(x, y) :
(document.caretRangeFromPoint ? document.caretRangeFromPoint(x, y):null);
if (range) {
range.collapse(false);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
}
Ensure to call this function in the right situation, meaning that the x and y coordinates should point to a position in the document
where there is an editable element in a focused state; otherwise, this code will not work.
I hope you find this solution helpful for your needs or learning purposes. Happy coding!