Hello fellow coders!
I was working on my tech doc. I have almost finished it, but there is no scrollbar appearing for the navigation menu I have. I tried adding overflow-y: auto; to the nav, but it’s not working. Can anyone help? Thanks in advance!
Thanks @jsdisco! It worked! However, the scrollbar is inside the main section. But, I will take care of it by changing the width of the navbar.
Thanks again for helping!
Hey @lendoo. Yes, I had tried to add a scroll spy effect for my menu. I had created a separate topic for it. I had watched the video you gave. But, it’s not a perfect solution. It will only work if the user is hovering over the section.
If that means that the scrollbar is too high and already starts at the header text “CSS documentation” - I gave max-height and overflow-y:auto to #navbar #links, not to #navbar. Not sure I understood you correctly.
Sorry, not max-height but height (although they could both work). You only get a scrollbar if some content (like your list of nav links) is longer than its container.
That being said, I find handling scrollbars a bit tricky, browsers don’t handle it consistently. It’s possible that you get a scrollbar by giving a max-width.
Thanks very much for your reply @jsdisco. One last thing, do you know how to add a scroll spy to my menu. I tried the intersection observer method that @lasjorg had suggested in this topic. . But, it doesn’t seem to work.
I have a little script snippet that I used for one of my projects once, but you’d have to customise it for your needs:
// list of all your sections
const sections = [
document.querySelector('#section1'),
document.querySelector('#section2'),
...
];
// list of all corresponding nav links
const navLinks = [
document.querySelector('#nav-link-1'),
document.querySelector('#nav-link-2'),
];
// finding out at which scroll y position a new section begins:
const breakpoints = sections.map(section => section.offsetTop);
// adding a scroll event listener that
// - reads the current y position
// - searches through the breakpoints array and either returns
// the corresponding index or 0 (if user hasn't scrolled to a section yet)
// - removes "active" class from all nav links
// - adds "active" class to the current nav link
window.addEventListener('scroll', ()=>{
const y = window.scrollY;
const currentIndex = breakpoints.find((b,i) => y > breakpoints[i]) || 0;
navLinks.forEach(link => link.classList.remove('active'));
navLinks[currentIndex].classList.add('active');
})
This is a very very basic solution. Adding a scroll event listener to a page is always a performance killer, but it’s ok for a challenge project I think, if only to get an idea how to do it.