views:

305

answers:

4

I have an HTML textarea:

<textarea>
Some text
Another text in another line

BOOM

Hello there.
</textarea>

I want to be able to vertically scroll to the word BOOM so that it is visible (it doesn't matter on which line it appears).

Is this possible?

A: 

depends... But no crossbrowser... Better forget it.... Textarea cant do many things....

Parhs
+1  A: 
$('textarea').animate({ 'scrollTop': 30 });

of course 30 is working for my own example with my cols and rows. so find the the right value for yourself.

Note to self:

There is no way of calculating the scroll height which a particular word is at however if you set a fixed value as your css line-height then you can see the story from the point of view that of boom is on for example the 4th line then its scroll height value is 4x (x:line-height) but i can't really right now be bothered to check how good that will work when someone zooms in the browser. but worth a try for you as you have the case.

XGreen
But how do I know that `BOOM` is 30 from the top?
Luca Matteis
A: 

But how do I know that BOOM is 30 from the top?

Create a <div>, add it to the page and style it with exactly the same font, white-space, dimensions, border, padding and overflow as the <textarea> object. Wrap the ‘BOOM’ in a <span>, and measure the position of the span relative to the position of the div.

(This isn't a lot of fun.)

bobince
+1  A: 

There's actually a way to do this using window.find() and some variation for IE browsers.

Here's what I came up with so far:

var gotoText = function(text) {
    function iefind(string) {
        var txt = document.body.createTextRange(); 
        if (txt.findText(string)) { 
            txt.scrollIntoView();
            txt.collapse(false);
        }
    }

    if(!window.find) { // ie
        iefind(text); 
        return;
    }

    // a double window.find() for backwards and forward search
    if(!window.find(text, false, true)){
       window.find(text, false, false);
    }
};
Luca Matteis