Active class on selected nav item - on same page (#id)


#1

I’m trying to add a current class to the active item in my nav bar. I can get it to work when linking to another page, but having issues when trying to link to a certain section via ID.

for example, my index.html has a section <div id="about">
and the nav is something like this:

<nav>
    <ul>
      <li><a href="{{ "index.html#about" | relative_url }}" class="{% if page.url == '/index.html#about' %}current{% endif %}">About</a></li>
      <li><a href="{{ "index.html#skills" | relative_url }}" class="{% if page.url == '/index.html#skills' %}current{% endif %}">Skills</a></li>
      <li><a href="{{ "contact.html" | relative_url }}" class="{% if page.url == '/contact.html' %}current{% endif %}">Contact</a></li>
    </ul>
</nav>

the current class on the contact link works fine, but i can’t get it to work for the about or skills sections.

thanks for any help.


#2

I’m not sure you will be able to get that to work via jekyll - page.url is a thing in jekyll when it builds your site - it does not mean the url that the browser has loaded (which could contain query strings or anchors) which is why it probably won’t work with the anchor #. There is only one index file, so how could it be both active and inactive for multiple anchors?

I’m sure you could do this with JS without much trouble.


#3

understood - i wasn’t aware that jekyll couldn’t recognize your page location. i will go the javascript way.
thanks for the reply!