Skip to content
Advertisement

Sidebar links not changing when the chapter titles are reaching the top on scroll, they change earlier

I have a sidebar with anchor links that point to a specific content part when I click on them.

The problem appears when I’m scrolling the content, the link in the sidebar gets highlighted when the section title barely appears at the bottom.

How can I make the link change when the title of chapter content reaches the top of sidebar?

Here’s what I tried so far but isn’t working exactly as I want.

JavaScript
JavaScript
JavaScript

Advertisement

Answer

The reason this is happening is because section.offsetTop is returning the position of the section relative to the offset parent. In this case the parent is the div that contains the sections <div class="col-sm-9">.

To fix the problem, we just need to adjust the value for the top of each section to take into account the distance of the parent from the top. We do this as follows:

1. Add an id to the parent container to make it easier to select, e.g.

JavaScript

2. Get the offsetTop of the parent so we can add this to the top of the section:

JavaScript

3. Calculate the actual top position in our scroll listener by adding the distance from the top of the parent container to the position of the section within the parent, which gives us its position from the top of the body in this case. Then we use this when we are checking how far the page is scrolled:

JavaScript

Working Example:
(FYI, you aren’t closing your li elements in your code, I fixed that here)

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement