Skip to content

DOM getBoundingClientRect()

Why getBoundingClientRect ?

The getBoundingClientRect () method returns the width, height, x and y coordinate, top, bottom, right, and left values ​​of the specified element. The amount of scrolling that has been done of the viewport area is taken into account when computing the bounding rectangle.

Syntax:

element.getBoundingClientRect()


Examples

Example 1

Press the F12 key. Open the console section. Review the codes.

getBoundingClientRect example
<body>

    <div class="box"></div>

    <script>

        let box = document.querySelector(".box");

        let react = box.getBoundingClientRect();

        console.log(react)


    </script>

Example 2

Press the F12 key. Open the console section. Review the codes.

getBoundingClientRect example
<body>

    <div class="box"></div>

    <script>

        let box = document.querySelector(".box");

        let react = box.getBoundingClientRect();
        

        console.log(react.width)
        console.log(react.height)
        console.log(react.bottom)
        console.log(react.top)
        console.log(react.left)
        console.log(react.right)

    </script>

</body>

Example 3

Examine the code below for an example.

getBoundingClientRect example
<body>

    <div class="container">
        <div class="image"></div>
        <div class="image"></div>
    </div>

    <script>

        document.querySelectorAll('.container').forEach((elem) => {
            let x, width
            elem.onmouseenter = () => {
                const size = elem.getBoundingClientRect()
                x = size.x
                width = size.width
            }

            elem.onmousemove = (e) => {
                const horizontal = ((e.clientX - x) / width) * 100
                elem.style.setProperty('--x', horizontal + '%')
            }
        })

    </script>
   
</body>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: