Infinite Scroll with TypeScript
How to implement infinite scrolling in HTML & TypeScript
Introduction
In this article, we will examine the process of implementing an infinitely scrolling list using HTML and TypeScript. Infinite scrolling is useful for content-driven websites and apps and is generally more appealing than classic pagination methods.
For the source code for the example project, see this repo.
To compile TypeScript, see this page or install it with node as follows:
$ npm install -g typescript
HTML
The HTML for this project contains some standard tags in the <head>
and defines a <header>
with project title along with a <main>
element which will be used to hold the infinite scrolling content. The compiled .js
file is included at the end of the body
section.
CSS
The CSS defines header and item height as variables, along with styles for the body
and content within. The main
element takes the full screen height minus the header
height. Items in the list will be of class main div
and contain some formatting based on the --item-height
variable.
TypeScript
The App
class has no constructor as it is meant to be static and contains only static methods and properties. The random_items
get accessor will return ten numbers between 0
and 10
which will be used to populate the list.
When init
is called, a reference to the scrollable container is retrieved, an event handler is attached for the onscroll
event, and load
is called, which grabs the next 10 items and calls append_item
for each.
The append_item
method creates a div
for the item along with a label
for the index of the item and a span
which will contain the random number. The item contents are set and it is then added to the list.
The scroll handler on_scroll
retrieves the height of an item on screen, and then calculates the scroll distance remaining based on the container scrollHeight
minus the scrollTop
and clientHeight
values. If the distance remaining is less than two items, load
is called to add more to the list.
Conclusion
That’s all there is to creating a simple infinite scrolling list using HTML, CSS, and TypeScript. This can easily be modified to retrieve actual items with an API call or some other method, using the length
of the list as an offset.
Thanks for reading and good luck with your next project!
~8_bit_hacker