Sunday, 26 November 2017

Make a list 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><a href="link2.html">Link2</a>
   <li><a href="link3.html">Link3</a>
   <li><a href="link4.html">Link4</a>
</ul>

CSS:

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

Include below script in each of the above links: 

//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'
   }
  });
 });

No comments:

Post a Comment