Skip to content

Commit e1164c4

Browse files
authored
Fix scroll position when opening a link with an anchor (#702)
* Fix scroll position when opening a link with an anchor * Cleanup
1 parent 3adcede commit e1164c4

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

src/Elastic.Markdown/Assets/pages-nav.ts

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,22 @@ function expandAllParents(navItem: HTMLElement) {
1111
}
1212
}
1313

14-
function scrollCurrentNaviItemIntoView(nav: HTMLElement, delay: number) {
14+
function scrollCurrentNaviItemIntoView(nav: HTMLElement) {
1515
const currentNavItem = $('.current', nav);
1616
expandAllParents(currentNavItem);
17-
setTimeout(() => {
18-
if (currentNavItem && !isElementInViewport(nav, currentNavItem)) {
19-
currentNavItem.scrollIntoView({ behavior: 'smooth', block: 'center' });
20-
window.scrollTo(0, 0);
21-
}
22-
}, delay);
17+
if (currentNavItem && !isElementInViewport(nav, currentNavItem)) {
18+
const navRect = nav.getBoundingClientRect();
19+
const currentNavItemRect = currentNavItem.getBoundingClientRect();
20+
// Calculate the offset needed to scroll the current navigation item into view.
21+
// The offset is determined by the difference between the top of the current navigation item and the top of the navigation container,
22+
// adjusted by one-third of the height of the navigation container and half the height of the current navigation item.
23+
const offset = currentNavItemRect.top - navRect.top - navRect.height / 3 + currentNavItemRect.height / 2;
24+
25+
// Scroll the navigation container by the calculated offset to bring the current navigation item into view.
26+
nav.scrollTop = nav.scrollTop + offset;
27+
}
2328
}
29+
2430
function isElementInViewport(parent: HTMLElement, child: HTMLElement, ): boolean {
2531
const childRect = child.getBoundingClientRect();
2632
const parentRect = parent.getBoundingClientRect();
@@ -41,8 +47,5 @@ export function initNav() {
4147
navItems.forEach(el => {
4248
el.classList.add('current');
4349
});
44-
scrollCurrentNaviItemIntoView(pagesNav, 100);
50+
scrollCurrentNaviItemIntoView(pagesNav);
4551
}
46-
47-
48-
// initNav();

src/Elastic.Markdown/Assets/styles.css

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
/* background-repeat: no-repeat;*/
3535
/*}*/
3636

37+
3738
#pages-nav li.current {
3839
position: relative;
3940
&::before {
@@ -87,6 +88,7 @@
8788
@apply sticky top-(--offset-top) z-30 overflow-y-auto;
8889
max-height: calc(100vh - var(--offset-top));
8990
scrollbar-gutter: stable;
91+
scroll-behavior: smooth;
9092
}
9193

9294
.sidebar-link {

0 commit comments

Comments
 (0)