Pages

Wednesday, July 17, 2013

Web Development/Jquery/Javascript-Set a menu Link "selected" class if its href matches page url

Here is a simple js code with HTML to set a "seected" class to menu item when its corresponding page is open.

 <dl class="sidebarBox">  
   <dt>Mailboxes</dt>  
   <dd>  
     <ul class="mailbar">  
       <li><a href="inbox"><b>Inbox</b></a></li>  
       <li><a href="sent">Sent</a></li>  
       <li><a href="trash">Trash</a></li>  
     </ul>  
   </dd>  
 </dl>  
 <script type="text/javascript">  
   var winpath=window.location.pathname;  
   $(".mailbar li a").each(function(index)  
   {  
     var menupath=$(this).attr('href');  
     if(menupath==winpath)  
       $(this).parent().addClass("current");  
     else  
       $(this).parent().removeClass("current");  
   });  
 </script>  

1 comment: