scrollIntoView Scrolls just too far
I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you'd see on a YouTube playlist next to the video player.
When a user visits the page, the option they are on is supposed to go to the top of the scrolling div. This functionality is working. The issue is that it goes just a tad too far. Like the option they are on is about 10px too high. So, the page is visited, the url is used to identify which option was selected and then scrolls that option to the top of the scrolling div. Note: This is not the scroll bar for the window, it is a div with a scrollbar.
I am using this code to make it move the selected option to the top of the div:
var pathArray = window.location.pathname.split( '/' );
var el = document.getElementById(pathArray[5]);
el.scrollIntoView(true);
It moves it to the top of the div but about 10 pixels too far up. Anyone know how to fix that?
Smooth scroll to the proper position
Get correct y
coordinate and use window.scrollTo({top: y, behavior: 'smooth'})
const id = 'profilePhoto';
const yOffset = -10;
const element = document.getElementById(id);
const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset;
window.scrollTo({top: y, behavior: 'smooth'});
Position Anchor By Absolute Method
Another way to do this is to position your anchors exactly where you want on the page rather than relying on scrolling by offset. I find it allows better control for each element (eg. if you want a different offset for certain elements), and may also be more resistant to browser API changes/differences.
<div id="title-element" style="position: relative;">
<div id="anchor-name" style="position: absolute; top: -100px; left: 0"></div>
</div>
Now the offset is specified as -100px relative to the element. Create a function to create this anchor for code reuse, or if you are using a modern JS framework such as React do this by creating a component that renders your anchor, and pass in the anchor name and alignment for each element, which may or may not be the same.
Then just use :
const element = document.getElementById('anchor-name')
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
For smooth scrolling with an offset of 100px.
You can do it in two steps :
el.scrollIntoView(true);
window.scrollBy(0, -10); // Adjust scrolling with a negative value here
If it's about 10px, then I guess you could simply manually adjust the containing div
's scroll offset like that:
el.scrollIntoView(true);
document.getElementById("containingDiv").scrollTop -= 10;
I solved this problem by using,
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
This makes the element appear in the center
after scrolling, so I don't have to calculate yOffset
.
Hope it helps...