views:

450

answers:

2

I have an HTML textarea as a basis for a small text editor running inside Chrome, which includes search functionality (as I need search features beyond what the browser offers). For longer texts, this means I need the JavaScript to scroll to the correct position after selecting the found text. This works fine by calculating the font's line height times the found text's row number (the latter I get by counting line breaks) and then setting textareaElement.scrollTop... but only when the textarea is set to wrap="off". When it wraps, as I sometimes need it, I cannot simply count the rows by counting line breaks, and my scroll position algo will be off by a bit.

What can I do to get the correct position of the found, selected text?

+2  A: 

I've tackled this issue for the search feature of the logging console in log4javascript. My code surrounds search results in tags whose style properties are changed as you flick through search results. Initially I called scrollIntoView() on the current search result span but I think I had problems in certain browsers (log4javascript supports IE 5, for example) and ended up writing my own scrolling function based on the offsetLeft and offsetTop properties of the span and the scrollLeft and scrollTop properties of the container. I suspect scrollIntoView() will work fine in Chrome though so you should be OK just using that.

Tim Down
Thank you for your answer; scrollIntoView() looks very interesting. I have to admit though I'm not using any div or span elements, so I think it doesn't work -- the thing I want to scroll into view is merely the currently selected text part within a large textarea element...
Philipp Lenssen
OK. I'm struggling to think of a way to achieve what you want. If your textarea is using a fixed width font and a fixed number of columns you could use that to caluclate the number of wrapped lines. Other than that, I can't see a way of doing it.
Tim Down
@Phillip Lenssen: You could surround the current selection with a temporary span scroll it into view then remove it using DOM manipulations, maybe?
A: 

Hi Philipp

I'm facing the same issue. if u have solved it pls post back ur solution.

cheers