DEV Community

Nikhil Chandra Roy
Nikhil Chandra Roy

Posted on

2 1

Javascript infinite scrollbar html section (Tutorial with practice)

Hi Friends,
We will continue our short tutorial,
today we are going to make a infinite scrollbar html section with the help of javascript getBoundingClientRect Method.
Let's begin

First html,

 <div class="wrapper">
        <section></section>
        <section></section>
        <section></section>
        <section></section>
        <section></section>
    </div>
Enter fullscreen mode Exit fullscreen mode

and second css

   section {
            height: 400px;
            background: linear-gradient(red, green);
            margin: 3rem;
        }
Enter fullscreen mode Exit fullscreen mode

our basic setup is ready.

now coming to the main point of javascript.

window.onscroll = (() => {
            let section = document.querySelectorAll('section')
            let wrapper = document.querySelector('.wrapper');
            let rect = section[section.length - 1].getBoundingClientRect()
            console.log(window.innerHeight)
            console.log(rect.y)

            if (rect.y < window.innerHeight) {
                for(let i = 0; i < 5;){
                    wrapper.innerHTML += `<section> </section>`
                    i++;
                }
            }
        })
Enter fullscreen mode Exit fullscreen mode

The onscroll event occur when the scroll down, so
we setup the section, wrapper variable and rect.

For rect variable with the help of getBoundingClientRect has "y" position of the window.
so we have make a condition

if (rect.y < window.innerHeight) {
                for(let i = 0; i < 5;){
                    wrapper.innerHTML += `<section> </section>`
                    i++;
                }
            }
Enter fullscreen mode Exit fullscreen mode

this condition occurs when the rect.y less than window.innerHeight.

for full code, you can follow my Codepen

if you interested like this short tutorial please like, share, follow me so that in the future I can make more tutorials just like this.
Thanks.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)