Click here to Skip to main content
15,861,125 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I like to keep my logo and menu bar in a header.php so that way its not such a pain to update it. However I just added interactivity to my menu bar and for each page I have to add active to the css class.

My menu code for the home page:
<ul> 
<li><a class="menubar active" href="index.php">Home</a></li> 
<li><a class="menubar" href="scores.php">Scores</a></li> 
<li><a class="menubar" href="players.php">Our Eagles</a></li> 
<li><a class="menubar" href="schedule.php">Game Schedule</a></li> 
</ul>


What I have tried:

I have tried nothing, yet, because I don't even know if this is possible.
Posted
Updated 6-Jul-16 19:26pm

1 solution

Of course, it's possible.
First thing first, remove the 'active' class from the Home menu.
You will need to write javascript code to accomplish this. When a page is loaded, the code will find the menubar link that matches the current page url and add the active class to it.
Take reference from
How to Add Active Class to a Navigation Menu Based on URL[^].
Consider where to put the css and javascript code so that they are only written once and simply be included in every page.
As an example, I have added the javascript code in the header.php.
HTML
<ul> 
<li><a class="menubar" href="index.php">Home</a></li> 
<li><a class="menubar" href="scores.php">Scores</a></li> 
</ul>
<script>
function addClass(){
  //Get the current page url	
  var pageurl = window.location.href;
  //Find all the anchor links with class name 'menubar'
  var menubar = document.getElementsByClassName('menubar');
  //Loop thru them to find the matching anchor link
  for(i=0;i<menubar.length;i++) { 
    //When the matching anchor link found
    if(menubar[i].href.toLowerCase()==pageurl.toLowerCase())    {
	  //Add 'active' to the existing class of the found anchor link
      menubar[i].className +=' active';
    }
  }
}
window.onload(addClass());
</script>
 
Share this answer
 
v5
Comments
Member 12622327 7-Jul-16 19:51pm    
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900