My goal is to create a never-ending horizontal scroll that allows users to scroll both left and right. When users scroll to the left, new content should be added to the beginning of the scrollable element (similar to scrolling through a schedule history). Conversely, when they scroll to the right, content should be appended.
I have noticed that browsers anchor content when scrolling up and down, which works perfectly as expected. This anchoring ensures that prepended content does not cause any sudden jumps in the scrolling experience.
However, the anchoring does not seem to work when scrolling horizontally (left or right). It feels as if the behavior is similar to having `overflow-anchor: none` set. How can I achieve the same smooth scrolling experience when moving left or right?
let topCounter = 0;
document.querySelector('.scrollable-top').scrollTo({ top: 100 });
document.querySelector('.scrollable-top').onscroll = (event) => {
if (event.target.scrollTop < 100) {
let box = document.createElement('div');
box.className = 'content-box';
box.textContent = `${topCounter--}`;
document.querySelector('.scrollable-top').prepend(box);
}
};
let leftCounter = 0;
document.querySelector('.scrollable-left').scrollTo({ left: 100 });
document.querySelector('.scrollable-left').onscroll = (event) => {
if (event.target.scrollLeft < 100) {
let box = document.createElement('div');
box.className = 'content-box';
box.textContent = `${leftCounter--}`;
document.querySelector('.scrollable-left').prepend(box);
}
};
.scrollable-top {
width: 200px;
height: 250px;
overflow-y: auto;
border: solid 1px black;
}
.scrollable-left {
display: flex;
width: 250px;
overflow-x: auto;
border: solid 1px black;
}
.content-box {
flex: 1 0 auto;
height: 150px;
width: 150px;
border: solid 1px red;
display: flex;
justify-content: center;
align-items: center;
}
<div class="scrollable-top">
<div class="content-box">1</div>
<div class="content-box">2</div>
<div class="content-box">3</div>
</div>
<div class="scrollable-left">
<div class="content-box">1</div>
<div class="content-box">2</div>
<div class="content-box">3</div>
</div>