Infinite scroller ( upwards ) gets stuck when going too fast

Viewed 209

I have an upwards infinite scroller. Like a message conversation, the newest is at the bottom, and you scroll up to load older messages. This works, but it gets stuck when going too fast. I have a 10px threshold from the top for the load function to trigger. Increasing this helps, but not full proof. When switching to a downwards infinite scroll, this works as intended and can go fast without ever getting stuck.

const scroller = document.getElementById( 'scroller' )
const list = document.getElementById( 'list' )

scroller.addEventListener( 'scroll', () => {
    if ( scroller.scrollTop < 10 ) load()
})

function load() {
    for ( let i = 0; i < 10; i++ ) {
    const li = document.createElement( 'li' )
    li.innerHTML = list.children.length + 1
    list.appendChild( li )
  }
}
load()
scroller.scrollTop = scroller.scrollHeight
#scroller {
  width: 150px;
  height: 150px;
  background-color: red;
  overflow-y: scroll;
}

ul {
  display: flex;
  flex-direction: column-reverse;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

li {
  background-color: white;
  width: 65%;
  border-radius: 4px;
  margin-left: auto;
  padding: 12px 16px;
  margin: 4px;
}
<div id="scroller">
  <ul id="list">
  
  </ul>
</div>

Also just to clarify what I mean, I will include the same infinite scroller but downwards, and you can see how its always smooth

const scroller = document.getElementById( 'scroller' )
const list = document.getElementById( 'list' )

scroller.addEventListener( 'scroll', () => {
    if ( scroller.scrollHeight - scroller.scrollTop - 10 <= scroller.offsetHeight ) load()
})

function load() {
    for ( let i = 0; i < 10; i++ ) {
    const li = document.createElement( 'li' )
    li.innerHTML = list.children.length + 1
    list.appendChild( li )
  }
}
load()
#scroller {
  width: 150px;
  height: 150px;
  background-color: red;
  overflow-y: scroll;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

li {
  background-color: white;
  width: 65%;
  border-radius: 4px;
  margin-left: auto;
  padding: 12px 16px;
  margin: 4px;
}
<div id="scroller">
  <ul id="list">
  
  </ul>
</div>

0 Answers
Related