Scrolling textarea to a specific area using javascript

I have a scroll box text box. I need to reposition your cursor in textarea using javascript and scroll the text box so your cursor is visible. I use elem.selectionStart and elem.selectionEnd to move the cursor, but when I move it to a point that is not visible, the text field does not scroll, so the cursor is visible.

More details (possibly TL; DR) I create a slide show editor and view the full slide show next to the editor (textarea with scroll bar) for the content. When you move the cursor through the text box, the slide show changes the slides, so you always see the slide that you are editing. I need this to change the slide (using the buttons), move the cursor so that you can see the code generated by this 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 lines in the file, so I know how far to scroll down, but there are a lot of long lines and take up a few lines. I use a monospace font, so I count the number of lines and lines that span multiple lines, but I would like to make an easier way. Is there a function that I could call to simulate what happens when the user moves his cursor, when the text field always scrolls to this point, when the user clicks ...

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

, , phantom, , . , , . . phantom textarea.

+5
1

, , .

  • phantom div, , div . , .

  • phantom div:

    visibility: hidden;
    position: absolute;

    , display: none, div .

. IE :

document.selection.createRange().scrollIntoView();
+2

All Articles