Is there a way to set the default scroll of an element to the max always so when you append new element to it it will scroll by default to the max like this
#elmnt{
default-scroll:max;
}
CodePudding user response:
You will have to manually scroll to the bottom after the element has been appended.
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
Check this here
CodePudding user response:
If you're inserting child elements into a parent container (like i.e: chat messages into a chat window), simply use Element.scrollTo(options)
elChat.scrollTo({top: elChat.scrollHeight, behavior: "smooth"});
Example:
const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
const elChat = el("#chat");
const addMessage = (textContent) => {
const elMsg = elNew("div", {className: "message", textContent});
elChat.append(elMsg);
elChat.scrollTo({top: elChat.scrollHeight, behavior: "smooth"});
};
let idx = 0;
el("#add").addEventListener("click", () => addMessage( idx));
#chat {
background: #eee;
height: 140px;
overflow: auto;
display: flex;
flex-direction: column;
gap: 0.5rem;
border: 2px solid #000;
}
.message {
background: gold;
padding: 1rem;
}
<button id="add"> ADD</button>
<div id="chat"></div>
another suggestion: by using Element.scrollIntoView() on the added child element.
elMessage.scrollIntoView({behavior: "smooth"});
Example:
const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
const elChat = el("#chat");
const addMessage = (textContent) => {
const elMsg = elNew("div", {className: "message", textContent});
elChat.append(elMsg);
elMsg.scrollIntoView({behavior: "smooth"});
};
let idx = 0;
el("#add").addEventListener("click", () => addMessage( idx));
#chat {
background: #eee;
height: 140px;
overflow: auto;
display: flex;
flex-direction: column;
gap: 0.5rem;
border: 2px solid #000;
}
.message {
background: gold;
padding: 1rem;
}
<button id="add"> ADD</button>
<div id="chat"></div>
Notice in the last example how every ancestor is scrolled in order for the message to get into view.