Home > front end >  getBoundingClientRect() returning wrong bottom value for a div element
getBoundingClientRect() returning wrong bottom value for a div element

Time:10-16

I have the following html and css code.

* {
    box-sizing: border-box;
    border: 0;
    margin: 0;
}

.image-slider {
    padding: 34px;
    width: 550px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    overflow-y: hidden;
}

.image-slider .images {
    display: block;
    margin: 14px 24px;
    border-radius: 15px;
}
<body>
    <div >
        <div >
            <img src="https://picsum.photos/400/300" alt="Img1" >
            <img src="https://picsum.photos/400/300" alt="Img2" >
            <img src="https://picsum.photos/400/300" alt="Img3" >
            <img src="https://picsum.photos/400/300" alt="Img4" >
            <img src="https://picsum.photos/400/300" alt="Img5" >
        </div>
    </div>
</body>

When I try to print get the getBoundingClientRect() of my image-slider div, it returns the following object.

{ 
    x: 0,
    y: 0,
    width: 550,
    height: 96,
    top: 0,
    right: 550,
    bottom: 96,
    left: 0
}

The height and bottom value is 96. But the actual height of the div turns out to be around 400px. Why is this happening? Am I missing out anything here?

Update1 I am basically trying to create an image viewer where left and right arrows appear on hovering on the left and right of the div. Please find my JS code. Due to the above issue, "Inside" only gets logged while hovering only on the top portion of the div.

const imageSlider = document.querySelector(".image-slider");
const coords = imageSlider.getBoundingClientRect();

imageSlider.addEventListener('mousemove', function(event) {
    if (!event) return;

    if (isMouseInsideTheImageSlider(event)) {
        console.log("Inside");
    }
})

function isMouseInsideTheImageSlider(event) {
    return event.clientX <= coords.right && event.clientX >= coords.left
        && event.clientY <= coords.bottom && event.clientY >= coords.top;
}

CodePudding user response:

You are trying to read the sizes of the element before the images are loaded, so the height is wrong. You should read the bounding rects after all images have loaded (move it inside the event listener or create some code to wait for all images to load).

  • Related