Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling textarea to specific area with javascript

I have a textarea with a scrollbar. I need to change the position of your cursor in the textarea with javascript AND scroll the textarea so your cursor is visible. I am using elem.selectionStart and elem.selectionEnd to move your cursor, but when I move it to a point that is not visible, the textarea does not scroll so the cursor is visible.

More details (probably TL;DR) I am creating a slideshow editor and have a preview of the complete slideshow next to an editor (textarea with scrollbar) for the content. As you move your cursor through the textarea, the slideshow changes slides so you are always viewing the slide that you are editing. I need to get it so changing the slide (using buttons) moves your cursor so you can see the code that generated that slide.

// slideBoundries has numbers which are the indexes where the slides begin/end
// eg: [0, 81, 140, 250] for slideshow with 3 slides

if (doc.editor.selectionEnd > slideBoundries[curSlide] &&
    doc.editor.selectionEnd < slideBoundries[curSlide + 1]) {
    return;
}
doc.editor.selectionStart = slideBoundries[curSlide];
doc.editor.selectionEnd = slideBoundries[curSlide];

I could just count the number of newlines in the file so I know how far to scroll down, but there are many lines that are long and take up multiple lines. I am using a monospaced font so counting the number of newlines and lines that take up multiple lines, but I would like an easier way. Is there a function I could call to mimic what happens when the user moves their cursor as the textarea always scrolls to that point when the user clicks...

EDIT: Due to popular demand, here is a fiddle: http://jsfiddle.net/tShQ2/

The method I'm going to use to fix this issue is create a phantom textarea that has same width, but autosizes to height. It has to be visible or else it won't work, so make it abs position and move it off screen. Then put the text before the desired cursor position in it. Then scroll the real textarea to the height of the phantom textarea.

like image 700
Bobby Avatar asked Nov 04 '22 16:11

Bobby


1 Answers

Your solution is a good one, but let me suggest a couple of things to make it easier.

  1. Use a phantom div, rather than a textarea, since a div will autosize automatically. Just make sure to match the styles.

  2. To hide your phantom div use:

    visibility: hidden;
    position: absolute;

    This has the same effect as display: none, while allowing the div to have a height.

One more thing. For IE, you can create a range from the selection and scroll to it explicitly:

document.selection.createRange().scrollIntoView();
like image 123
gilly3 Avatar answered Nov 11 '22 05:11

gilly3