Editor: move caret to a specific position


#1

Hi All,

I want to move the caret to a specific part of my draft after some actions ran. I’ve been checking the editor but couldn’t find a way. Is there a way? (Sorry newbie question I know! Trying to learn so pls bear with me :grinning: )

Thanks


#2

Use setSelectedRange() on the editor object. You can pass a 0 for the length of the range, which will just position the insertion-point.


#3

Using the following, but not working. Definitely doing something wrong here…

var text = "this is the main text"

Draft content = text;
Draft.update();

editor.setSelectedRange(text[0]+10,0);
editor.activate();

#4

Here’s an action that I’ve been using for something similar. It is hard coded to find the “### Discussion” header as the place to move the cursor. You can change that to meet your needs.

Hope this helps — jay

// move cursor to line following the found text
// 
// text to find
const headerName = "### Discussion";
var headerLength = headerName.length;
var d=draft.content;
var headerStart = d.search(headerName);
// +1 to move to next line
editor.setSelectedRange(headerStart+headerLength+1,"");
editor.activate();

#5

There’s, uh, quite a lot wrong there. First, you’re missing a semicolon at the end of the declaration of the variable text. Second, you’re using Draft (the class name) instead of draft (the variable holding the implicit instance of the current draft). Third, you’re missing the period before using content as a setter, to put your text into the draft. Fourth, you seem to be unclear on what a range is: it’s two numbers, the first of which is the starting position, and the second of which is a length. What you’ve passed to setSelectedRange() is the first character of text, plus ten, with a length of zero. And a possible fifth issue is that if you’re not running this with an open draft, there won’t even be an implicit draft object to refer to.

To start with, I’d read the docs on the Draft and Editor objects again. Here’s a quick untested edit to your code.


#6

Thanks hay. This definitely helps!! Will try it out.


#7

Thanks Matt for taking the time to such an extensive reply. My script is right in drafts but I wrote these lines in a rush so forgot about all semicolons, dots and lower case letters - will be more careful next time cause it matters :grinning: (I’m very novice in scripting as one can tell…but learning!!)

The bit that was not right at all is the setSelectedRange… I understand now how to use it. Yours and Jay’s replies made it clear. Appreciate.


#8

And it works!! You guys rock!! :smile:


#9

:+1: glad you figured it out!