How to Change Color of Link When Reaching a Section?

Hey everyone!
I was creating my tech doc project and was wondering how to change the color of the link in the menu when it reaches the corresponding section assigned to it. For example, I want something like this:

When I am in Introduction:

When I am in another section:

Thanks in advance!

The term you’re looking for is “scrollspy”.

1 Like

Thanks @jenovs. I didn’t knew the term for it!

You need to add a class on each html page in the specific anchor tag which you want to look different from other anchor tags. Then apply the specific CSS rule to that class attribute that makes the active page link different from other links.

For Example:

//HomePage


  • <a href=“home.html” class="current">Home

  • Products


//Product Page


  • Home

  • <a href=“product.html” class="current">Products


//CSS Styling
ul {
list-style: none;
}
ul li {
display: inline-block;
}
ul a {
display: inline-block;
text-decoration: none;
color: black;
background-color: white;
}
ul a:hover {
background-color: black;
color: white;
}
ul a.current {
background-color: green;
color: white;
}

// I hope its clear now :slightly_smiling_face:

1 Like

Here is an example using IntersectionObserver, the JS code has links to MDN and an article

1 Like

Hi @princeovais. Your solution should have worked if my project was multipage. But, I am building the technical documentation project and want this effect for internal links.
Anyway, thanks for sharing!

I will give it a try @lasjorg. But, is there any CSS or simple JS option for this. I don’t understand this code (I will watch a video, of course)!
Thanks!

I’m sure if you search for examples you can find a bunch. Some will just use a scroll event and some document/element position properties. If you search for something like highlight link on scroll you will likely get more pure results back as it will avoid a lot of Bootstrap and libraries. If you just want the functionality using a library is always an option.

I know IntersectionObserver code looks a little funky at first but it’s really not that bad and it’s a very handy API to know about.

1 Like

Hi, @lasjorg. Thanks for your help. It kind of works, but not correctly. If I am in the “CSS Comments” section, it would change the color of the “CSS Backgrounds” link. Can’t understand why. Also, I am not very comfortable with JS (just knows the basics).

Here is the pen: