Back

Technologies:

javascriptjavascript
avatar
Tolerim
24 days ago

How can I create an infinite scroll on both sides using JavaScript?

The following code was developed to save memory when loading a page that displays DB rows containing thousands of values. The code appends data to a container by mapping through an object's values to create a HTML string to be inserted, using the insertAdjacentHTML() method. When the window is scrolled and the scrollTop + clientHeight is greater than or equal to scrollHeight - 5, the loadMore() function is triggered to fetch more data and append it. The code also limits the number of items displayed to maxItemCount and removes items from the container when the limit is exceeded. However, the code doesn't work when scrolling up. Assistance is requested to fix the issue.
Answers(2)
avatar
Vogi
22 days ago
Verified Answer
It seems that the issue is related to the scrollTop property. According to this StackOverflow post, the script won't work in Chrome unless you set the container style to overflow: auto, or overflow: scroll. Chrome simply ignores the element.scrollTop setter otherwise. So, you might want to check if your container has this style. Also, according to this Mozilla Developer Network page, scrollTop is a non-rounded number, while scrollHeight and clientHeight are rounded — so the only way to determine if the scroll area is scrolled to the bottom is by seeing if the scroll amount is close enough to some threshold (in this example 1): Math.abs(element.scrollHeight - element.clientHeight - element.scrollTop) < 1; I hope this helps! Let me know if you have any other questions.

Sources

scrollTop = scrollHeight does not work in ChromeAngular: element.Scrolltop = element.scrollheight isn't workingElement: scrollHeight property - Web APIs | MDN - Mozilla Developer
avatar
Tolerim
24 days ago
It seems like you are trying to add infinite scrolling to load more data when scrolling down the page and also trying to add a feature to load data when scrolling up. The code you provided shows an implementation of infinite scrolling to load more data when scrolling down. However, you mentioned that you tried to modify the code to load more data when scrolling up but didn't get the expected result. It would be helpful if you could provide more information about the expected result and the code modifications you made so that I can provide better assistance.
;