DEV Community

Cover image for How to use getBoundingClientRect() Javascript Method scroll effect (Tutorial with Practice)
Nikhil Chandra Roy
Nikhil Chandra Roy

Posted on

How to use getBoundingClientRect() Javascript Method scroll effect (Tutorial with Practice)

Alt Text
Hi Friends,
Today we are going to learn how to use a custom scroll effect when scrolling down.

There is a cool slider called AOS
but we are going to use vanilla javascript to use it as the same effect when scrolling the page.

first, we are going to add 10 sections. for emmet section*10 vs code

    <section></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>
    <section></section>

Enter fullscreen mode Exit fullscreen mode

CSS

section {
            height: 300px;
            background: red;
            margin-bottom: .5rem;
            transition: .5s;
        }

Enter fullscreen mode Exit fullscreen mode

and javascript

  let section = document.querySelectorAll('section')

        window.onscroll = (() => {
            section.forEach(function(v) {
                let rect = v.getBoundingClientRect();
                let y = rect.y;
                if (y > window.innerHeight) {
                    v.setAttribute('style', 'opacity: 0; transform: translateY(100%)');
                } else {
                    v.setAttribute('style', 'opacity: 1; transform: translateY(0%)');
                }
            })
        })

Enter fullscreen mode Exit fullscreen mode

the getBoundingClientRect() method has some object such as:

  • x
  • y
  • width
  • height
  • top
  • bottom we have used y cordination and for more details about this getBoundingClientRect() we can follow some usefull links.

below some usefull links to learn more about getBoundingClientRect() Js method.

Thanks, for today. If you interested in this short tutorial please like comment and follow.
Bye

Discussion (0)