0

How to highlight every link in main menu with a different color based on its current page ?

for example change the contact us link color to red in the main menu when the current page is contact us
and change the about us link color to orange in the main menu when the current page is about us and so on

Piyush Marvaniya
  • 2,496
  • 2
  • 16
  • 28

4 Answers4

2

You can use javascript to do this:

first, retrieve your current url path:

var pathname = window.location.pathname;

for example, return "/contact.html" then you can use this value to detemine which item to be hilighted:

if(pathname == "/contact.html"){
   document.getElementById("contact").addClass("hilighted");
}

and so on.

vtproduction
  • 147
  • 3
  • 10
0

a:active : when you click on the link and hold it.
a:visited : when the link has already been visited.

If you want the link corresponding to current page to be highlighted, you can define some specific style to the link -

.current {
   color: red;
   background-color: #000000;
}

Add this new class .current only to the corresponding li (link), either on server-side or on client-side (using javascript/jquery).

With JQuery you could use the .each function to iterate through the linkswith the following code:

$(document).ready(function() {
    $("[href]").each(function() {
    if (this.href == window.location.href) {
        $(this).addClass("current");
        }
    });
});

Depending on your page structure and used links, you may have to narrow down the selection of links like:

$("nav [href]").each ...

if you are using url parameters, it may be necessary to strip these:

if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...

This way you don't have to edit each page.

source

Community
  • 1
  • 1
4dgaurav
  • 11,360
  • 4
  • 32
  • 59
0

There are a lot of approaches, it's hard to say which is best without seeing your code.

You could use some Javascript on each page to add or change the class of your links.

For instance on your contact us page use a a script like

var contactLink = document.getElementById("contactUs");
contactLink.addClass("orangeLink");
lwalden
  • 813
  • 7
  • 11
0

You can add active class to the menu based on current page.

if you are in contact page then add active class to contact us menu, same for about us page, then do some css for that active class.

for example if you are in contact-us page then :-

<ul>
    <li class="home"><a href="home.html">Home</a></li>
    <li class="contact active"><a href="contact-us.html">Contact Us</a></li>
    <li class="about"><a href="about.html">About Us</a></li>
</ul>

Now do some css for that :-

.contact.active{
   color : red;
}
.about.active{
   color : orange; 
}

It will worked for you.

Harsh Sanghani
  • 1,666
  • 1
  • 14
  • 32