Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element.scrollIntoView cuts off the top

I am trying to scroll elements into view using the .scrollIntoView() function in JavaScript.

section.reference.value.scrollIntoView(
                            {
                                behavior: "smooth",
                                "block": "start",
                                "inline": "start"
                            }
                        );

It almost works perfectly, it scrolls everything necessary to show the element, except it always cuts it off by about 10px, and I don't think there is an option to give it an offset when scrolling.

Does anyone know how to do this?

like image 515
Jamzy01 Avatar asked Oct 31 '25 19:10

Jamzy01


2 Answers

To use JavaScript scrollIntoView to do smooth scroll with offset, you can call scrollTo with an object that has the top and behavior properties.

const element = document.getElementById("targetElement"); // Your target element
const headerOffset = 45;
const elementPosition = element.getBoundingClientRect().top;
const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

window.scrollTo({
  top: offsetPosition,
  behavior: "smooth",
});
like image 153
Sanket Shah Avatar answered Nov 02 '25 09:11

Sanket Shah


I fixed this by just creating a temporary element inside that element, and moving it using relative positioning to account for my own offset, then deleting it right after.

like image 28
Jamzy01 Avatar answered Nov 02 '25 10:11

Jamzy01



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!