-2

I am making a web chat. I have a div called chatbody. I want the div to scroll to bottom using javascript so that the last message is displayed. However, the code that I am using scrolls it to top instead. Here is the code:

<script type="text/javascript">
function chatbody() {
var myDiv = document.getElementByClassName('chatbody');
myDiv.innerHTML = variableLongText;
myDiv.scrollTop = 0;
} 
</script>

Kindly assist to solve my issue.

YUSUF KIPROP
  • 63
  • 2
  • 8
  • *"However, the code that I am using scrolls it to top instead"* No, it isn't. It's failing with a `TypeError`, there is no `getElementByClassName` function on `document` (unless you've added one, of course). There's `getElementsByClassName` (note the plural) which [returns a list](http://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method), not a single element. – T.J. Crowder Jul 12 '17 at 10:35
  • Separately: If your code **did** scroll to the top, if you think about it for a moment and do some research, you should be able to make it scroll to the bottom instead. Consider: What would you need to change? What is this `scrollTop` thing? – T.J. Crowder Jul 12 '17 at 10:36
  • Possible duplicate of [Scroll to bottom of div?](https://stackoverflow.com/questions/270612/scroll-to-bottom-of-div) – prasanth Jul 12 '17 at 10:39

2 Answers2

0

Try This

var myDiv = document.getElementByClassName('chatbody')[0];

Pioter
  • 465
  • 3
  • 8
  • 21
0
  function scrollToBottom(nameOfBlock) {
  nameOfBlock.scrollTop = nameOfBlock.scrollHeight
  }

U can pass your variable as an argument

Anton_L
  • 89
  • 8