Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop a textarea from scrolling to the top whenever I change its value

I'm making something where a textarea gets more and more text appended. In firefox, the textarea scroll back up to the top each time. I currently have something like textarea.scrollTop=1000000; to scroll it back down each time it changes, but it still goes up to the top for a very short time. Is there any way to stop it doing so?

like image 248
tmim Avatar asked Jul 08 '10 10:07

tmim


People also ask

How do I stop textarea from scrolling?

Re: Is it possible to disable textarea auto grow and show scrollbar. you can add data-role="none" to the textarea tag.

What is scrollTop()?

The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0.

What is window onscroll?

Definition and Usage. The onscroll event occurs when an element's scrollbar is being scrolled. Tip: use the CSS overflow style property to create a scrollbar for an element.


1 Answers

I ran into this problem, too. It happens in IE and Firefox but not Opera and Chrome.

I thought of hiding the momentary jumps to the top by "double-buffering" changes to the textarea:

  1. Create two textareas with the exact same properties and dimensions. Only one of these is visible; the other one is hidden.
  2. Append text to the hidden textarea: set [the value of the hidden textarea] to [the value of the visible textarea] + [text to append]. (The textarea will automatically scroll to the top, but this textarea is hidden!)
  3. Scroll the hidden textarea to the bottom: set scrollTop to a high integer value like (-1 >>> 1).
  4. Swap the hidden textarea with the visible one. Now the new text is shown, sans jumping to top!

You can swap the hidden/visible textareas by using one of two methods:

  1. Use absolute positioning to place the textareas on top of each other in conjunction with toggling their visible property.
  2. Swap the actual DOM elements. I'm not sure if this will introduce a new type of "flicker." You may have to create a div to contain the visible textarea so the layout of the page doesn't keep changing...
like image 110
Leftium Avatar answered Oct 21 '22 03:10

Leftium