Implement Infinite Scroll with pure/Vanilla JS

yeshwanth hp
2 min readApr 5, 2020

--

I’m pretty sure we all have spent hours just scrolling through Social media feeds just a push of thumb boom you have it.

Well popular libraries have great packages that make this feature look effortlessly cool. But i bet as a programmer nothing makes one feel more elated than getting a thing done from scratch.

Enough talking bring me the code…

Well not so early first let’s know what we’re cooking

Since its Vanilla JS it’s a no brainier all we need is some HTML and handful of JS and some CSS to spice things up.

Well lets start cooking…

Start of with a basic HTML layout and some CSS which you can find in my Pen https://codepen.io/luftwaffe/pen/YzXoZew

For all you folks who want to stay for long run

Here’s the receipe

  1. Just load your page with first data set from API

2. Then add a scroll listner easy peasy(hoping your throttle or debounce are in check else you know your page is messed up)

Here’s an interesting read about debouncing and throttling

https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf

3. Well coming back what’s a throttle handler…

let trottleHandler = () =>{throttle(handleLoad.call(this), 1000)};

4. Woh handleLoad what’s this thing !!!

Well nothing crazy just a cute little Js method

Here’s what it does,

just check if page bottom is about to be reached just have an offset of few pixels from bottom

Just check if you are not on the last page

increament your page by one

Here’s a gotcha if you do not unbind your scroll listner before the API call multiple API requests will be fired at the same time which is bad just unbind it.

After successful fetch just add back the scroll listner

Populate UI with new data

That’s it you are done works like charm is n’t it??

5. Just a another gotcha make sure your new DOM elements are attached to event listeners and old DOM elements are not corrupted with duplicate listerners.

Well that’s it folks enjoy your meal!!!

Once again here’s link to full code

Hope you enjoyed the meal leave a clap or two.

Bye happy coding!!!!

--

--

yeshwanth hp

A world war geek,a trekker, a badminton lover, a continuous learner and may be a programmer