javascriptdomgetboundingclientrect

what is the difference between .getBoundingClientRect().top and .getBoundingClientRect().y in javascript?


im really confused about the difference between these two methods. every time i use theme the have the same value so what is the difference?

heres the code i tried as an example.

const btnGetCoord = document.querySelector(".get--section--coordination");
const section1 = document.querySelector("#section--1");

btnGetCoord.addEventListener("click", (e) => {
    const sec1Coords = section1.getBoundingClientRect();
    console.log(sec1Coords.y);
    console.log(sec1Coords.top);
});

// html code
<button class="get--section--coordination">get section 1 coordination</button>
    <div style="background-color: green;width: 100vw;height: 2000px"></div>
    <section id="section--1">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium blanditiis dolorum
        ducimus, eius eligendi eos error et eum explicabo fugiat fugit iure laboriosam maiores natus nesciunt
        perspiciatis provident quia quidem quo ratione repellat rerum saepe sed. Blanditiis impedit nulla porro
        praesentium quas ut voluptate. Dolores, et voluptates? Consequatur quidem, voluptates.
        </p>
    </section>

why are they always the same and if not what is the difference?


Solution

  • getBoundingClientRect is returning a DomRect object.

    y:

    The y coordinate of the DOMRect's origin (typically the top-left corner of the rectangle).

    top:

    Returns the top coordinate value of the DOMRect (has the same value as y, or y + height if height is negative).

    So the two are equal indeed, unless height is negative, in which case top will be equal to y + height