CodeBlue
CodeBlue

Reputation: 15389

How to set the scrollTop value for a textarea?

I am facing a problem when I try to set the scrollTop value for a textarea. 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 to make the textarea somehow automatically be scrolled down to the maximum when the text does not fit in the actual width and height and the scroll bar gets activated.

Here's are two screenshots explaining the problem -

This is what I have currently -

enter image description here

And this is what I would like to have -

enter image description here

Please help!

Upvotes: 6

Views: 8995

Answers (3)

Nathan G
Nathan G

Reputation: 1781

I believe that setting the scrollTop in FF does not work when overflow of the element is visible. It works if the overflow is hidden

Upvotes: 0

Lawrence Cherone
Lawrence Cherone

Reputation: 46610

Also had issues with using scrollTop in firefox with textarea, especially if textarea value is set with 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>

Upvotes: 0

CodeBlue
CodeBlue

Reputation: 15389

Ok, sorry guys. The problem was that I was getting the wrong text area. 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!

Upvotes: 1

Related Questions