How to set scrollTop value for text field?

I am having a problem when I try to set the scrollTop value for a text field. My JavaScript code is as follows:

var element = document.getElementById("messageTextArea"); console.log("scrollTop = "+element.scrollTop); console.log("scrollHeight = "+element.scrollHeight); element.scrollTop = element.scrollHeight; // doesn't work! console.log("The value is-->"+element.scrollTop); // no change! element = document.getElementById("messageTextArea"); console.log("Now scrollTop = "+element.scrollTop); // no change! console.log("Now scrollHeight = "+element.scrollHeight); 

The Firefox console log gives the following:

 scrollTop = 0 scrollHeight = 86 The value is-->0 Now scrollTop = 0 Now scrollHeight = 86 

What I really want to do is make sure that textarea automatically scrolls to the maximum when the text does not match the actual width and height, and the scroll bar is activated.

Here are two screenshots explaining the problem -

This is what I have at the moment -

enter image description here

And this is what I would like to have -

enter image description here

Please, help!

+4
source share
3 answers

This works for me http://jsfiddle.net/7uXKX/6/ .

+1
source

Okay, sorry guys. The problem was that I received the wrong area of ​​text. This is so embarrassing! Now it works.

  var element = document.getElementById("chatTextArea"); // <-- this is where I was making a mistake in my code. So embarrassing! 
+1
source

There were also problems using scrollTop in firefox with textarea , especially if textarea was set using AJAX.

This worked for me:

 <script> function scroll_bottom(elm){ var elm = document.getElementById(elm); var bottom = function() { elm.scrollTop = elm.scrollHeight; }; setTimeout(bottom, 0); } </script> 

Then, to use it, for example:

 <textarea id="log" style="width:100%;height:100%;resize:none;"></textarea> <script> $(document).ready(function(){ scroll_bottom('log'); }); </script> 
0
source

Source: https://habr.com/ru/post/1400469/


All Articles