How to scroll to the active page in navigation drawer when opening it #4025
-
|
Hello, having a problem with the navbar focus. Normally when you have a standalone navbar it'll scroll and focus on the active page. Is there a way to fix this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
This is a common UX issue with MkDocs (and Material for MkDocs) when the navigation drawer opens on small screens. The default behavior doesn't auto-scroll to the active item. You can fix this with a small JavaScript snippet. Add it to your document.addEventListener("DOMContentLoaded", function () {
var toggle = document.querySelector('[data-md-toggle="drawer"]');
if (toggle) {
toggle.addEventListener("change", function () {
if (this.checked) {
// Small delay to let the drawer animate open
setTimeout(function () {
var activeLink = document.querySelector(
".md-sidebar--primary .md-nav__link--active"
);
if (activeLink) {
activeLink.scrollIntoView({ block: "center", behavior: "instant" });
}
}, 100);
}
});
}
});Then reference it in your extra_javascript:
- javascripts/extra.jsThe script listens for the drawer toggle checkbox changing state, waits briefly for the animation, then scrolls the active nav link into view. The If you're using vanilla MkDocs (not Material), the selectors will be different -- you'd look for whatever class your theme uses to mark the active nav item. Check your theme's output HTML to find the right selector. |
Beta Was this translation helpful? Give feedback.
-
|
@manimovassagh Thanks!! I had to make some slight adjustments for my project. document.addEventListener("DOMContentLoaded", function () {
var toggle = document.querySelector('[data-md-toggle="drawer"]');
if (toggle) {
toggle.addEventListener("change", function () {
if (this.checked) {
// Small delay to let the drawer animate open
setTimeout(function () {
var activeLink = document.querySelector(".md-nav__item .md-nav__item--active");
if (activeLink)
{
activeLink.scrollIntoViewIfNeeded(true);
}
}, 50);
}
});
}
}So using And |
Beta Was this translation helpful? Give feedback.
This is a common UX issue with MkDocs (and Material for MkDocs) when the navigation drawer opens on small screens. The default behavior doesn't auto-scroll to the active item.
You can fix this with a small JavaScript snippet. Add it to your
docs/javascripts/extra.js: