Home > front end >  How do I bring underline in Navbar in accordance to the page visited?
How do I bring underline in Navbar in accordance to the page visited?

Time:03-20

I want navbar to underline the currently visited page just like in the below picture-

enter image description here

CodePudding user response:

A way I find works for me is to just check the path current url of the page with location.pathname and compare it with whatever you want to name it, and then apply the appropriate class to it.

Here is some example code:

const pathMap = {
  '/': document.getElementById('home_nav'),
  '/about': document.getElementById('about_nav'),
  '/contact': document.getElementById('contact_nav'),
  '/projects': document.getElementById('projects_nav'),
};

const path = location.pathname;

if (pathMap[path]) {
  pathMap[path].classList.add('active');
}

You have to add this code to wherever your navbar is located. Keep in mind there might be better ways to do this, but if you only run this code where your navbar exists then there should be no problem. Another draw back is that this way does not support nested paths, so lets say you are at /projects/cat-hotel then it won't work properly, of course you can do some RegEx to solve this but I am just showing you an example.

CodePudding user response:

I have used these two solutions and they worked just fine for me.

https://css-tricks.com/forums/topic/how-to-keep-the-page-highlighted-on-the-nav-bar/

https://css-tricks.com/forums/topic/highlight-nav-links-when-scrolling-the-page/

  • Related