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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With