DEV Community

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

Posted on

1 1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

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

Learn more

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

When you're signed in, DEV shines by unlocking a customized experience packed with features like dark mode!

Okay