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

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)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up