Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto-scroll to the bottom of a div perpetually?

I have a <div> with scrolling. Through JavaScript I add elements to the <div> with element.scrollTop = element.scrollHeight. Works great except I have to do that every time an element is added to the <div>. Is there a way to auto-scroll (without using setInterval and repeatedly scrolling over and over) and keep the <div>'s scrollbar pegged to the bottom?

My <div>:

<div class="messages" style="height: 7em; overflow: scroll">
  <div>Anonymous: Hello</div>
  <div>John: Hi</div>
</div>

Is there a <div> event for when the content changes?

UPDATE: I don't have easy access to JavaScript code after the <div> is added. That's why I'd love to add an event listener or some other mechanism to keep the scroll bar pegged to the bottom.

like image 855
at. Avatar asked Oct 30 '22 15:10

at.


1 Answers

Create a variable var index = 0. Add tabIndex attribute to the dynamically created element with index set as .value of tabIndex attribute. Call .focus() on dynamically created element after appending element to parent element.

var index = 0;

var div = document.createElement("div");
div.setAttribute("tabIndex", index);
document.querySelector(".messages").appendChild(div);
div.focus();
++index; 

window.onload = function() {
  var messages = document.querySelector(".messages");
  var index = 0;
  setInterval(function() {
    var div = document.createElement("div");
    div.setAttribute("tabIndex", index);
    div.innerHTML = "abc";
    messages.appendChild(div);
    div.focus();
    ++index;
  }, 2000)
}
<div class="messages" style="height: 7em; overflow: scroll">
  <div>Anonymous: Hello</div>
  <div>John: Hi</div>
</div>

plnkr https://plnkr.co/edit/34QUtpGNVfho2fmYIlUI?p=preview

like image 141
guest271314 Avatar answered Nov 09 '22 23:11

guest271314