The useful Element.scrollHeight read-only property is a measurement of the height of an element's content, including content not visible on the screen due to overflow.
Some prerequisites
To determine if a scrollable element has been totally scrolled:
const has_been_totally_scrolled =
element.scrollHeight - Math.abs(element.scrollTop) === element.clientHeight;
To determine if an element can scroll:
window.getComputedStyle(element).overflowY !== "visible" &&
window.getComputedStyle(element).overflowY !== "hidden";
element.scrollTop, element.clientHeight and element.scrollTo
Examples
Checking that the user has read a text
This is a pretty common scenario in which some process can't be continued unless the user has scrolled through all the content.
The following code line is to check if the reading has been finished:
checkReading.read =
this.scrollHeight - Math.round(this.scrollTop) === this.clientHeight;
show the latest chat record
This is an demo from svelte. The idea is very brilliant. But I think the demo code is not very reasonable and perhaps have some bug such as when the vertical scrollbar appear and you scroll up to see the first sentence and then type your reply, you will not see the latest chat record.
So I change this block of code:
beforeUpdate(() => {
autoscroll = div && div.offsetHeight + div.scrollTop > div.scrollHeight - 20;
});
afterUpdate(() => {
if (autoscroll) div.scrollTo(0, div.scrollHeight);
});
into this:
afterUpdate(() => {
// ...the DOM is now in sync with the data
autoscroll = div.scrollHeight - Math.abs(div.scrollTop) !== div.clientHeight;
if (autoscroll) {
div.scrollTo({
top: div.scrollHeight,
left: 0,
behavior: "smooth",
});
}
});
In short, I changed the definition and position of conditional statement of autoscroll to make the scroll behavior more reasonable and precise.
The final effect is as follows: