Make a list menu element active when included using php include

Often there is a requirement to make a menu element active when we import something using php include. Its quite simple and this is how its done.

<? php include "includes/sidebar.php"; ?>  

(sidebar.php):

<ul id="sidebar">
  <li><a href="link1.html">Link1</a></li>
  <li><a href="link2.html">Link2</a></li>
  <li><a href="link3.html">Link3</a></li>
  <li><a href="link4.html">Link4</a></li>
</ul>

CSS:

ul#sidebar > li.active {
 background-color:#6495ED;
 color:#fff;
}

JavaScript (jQUery solution):

//current url being access
 var cur_href = window.location.href;
 $(document).ready(function(){
  $("#sidebar li a").each(function(){
   //get current href link
   var cur_attr =$(this).attr('href');  
   //save into regex
   var regex = new RegExp(cur_attr,"ig");
   //test if current link and current href matched
   if(regex.test(cur_href)) {
    $(this).parent().addClass('active'); //if yes then addClass 'active'
   } else {
    $(this).parent().removeClass('active'); //else removeClass 'active'
   }
  });
 });

This will make current menu link active in sidebar.

Start a Conversation

Your email address will not be published.