Luca Matteis
Luca Matteis

Reputation: 29267

HTML textarea; scroll vertically to text

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?

Upvotes: 4

Views: 3639

Answers (4)

Carmelo
Carmelo

Reputation: 1

It's possible with some javascript! Even if I'm late I hope it can be usefull to someone else!

I published an answer here:

http://blog.blupixelit.eu/scroll-textarea-to-selected-word-using-javascript-jquery/

It works perfectly with jsut one needed rule: Set a line-height n the css of the textarea!

It calculate the position of the word to scroll to just by doing some simple mathematic calculation and it worked perfectly in all my experiments!

Feel free to ask me anything you need about the code!

Upvotes: 0

Luca Matteis
Luca Matteis

Reputation: 29267

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);
    }
};

Upvotes: 3

bobince
bobince

Reputation: 536715

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.)

Upvotes: 1

Ali Habibzadeh
Ali Habibzadeh

Reputation: 11578

$('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.

Upvotes: 1

Related Questions