Friday, April 19, 2013

Navigation menu to show current page link as active - jquery

Hi, now am going to share a small article here, that is how to show current page link as active in navigation  menu using JQuery.
First we need to include JQuery library into the page.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
before that we need to maintain the left menu in separate page and include it the required pages.
assume take a left menu page leftmenu.php
<div id="left_menu_div">
<ul>
<li id="menuitem1" title="menu item 1"><a href="http://localhost/activemenu/page1.php">Page One</a></li>
<li id="menuitem2" title="menu item 2"><a href="http://localhost/activemenu/page2.php">Page Two</a></li>
<li id="menuitem3" title="menu item 3"><a href="http://localhost/activemenu/page3.php">Page Three</a></li>
<li id="menuitem4" title="menu item 4"><a href="http://localhost/activemenu/page4.php">Page Four</a></li>
</ul>
</div>
then add your css in the page
<style type="text/css">
#left_menu_div ul
{
 list-style-type:none;
 font-size:11px;
 line-height:23px;
 border:0px solid #ccc;
}

#left_menu_div ul li {
 margin-bottom:5px;
 outline: 0;
 padding: 3px 3px 3px 6px;
 display: block;
 font-weight: bold;
 border: 1px solid #1c252b;
 border-left:5px solid #ee6e28;
 border-radius: 4px;
 -moz-border-radius: 4px;
 -webkit-border-radius: 4px;
 box-shadow: 1px 1px 1px rgba(0,0,0,0.2); /* CSS3 */
 -moz-box-shadow: 1px 1px 1px rgba(0,0,0,0.2); /* Firefox */
 -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,0.2); /* Safari, Chrome */
 background:#2a69bf;
 width:180px;
 color:white;
}
#left_menu_div ul li a{
 text-decoration:none;
 font-size:14px;
 color:white;
}

.active {
    background: #0186ba;
 background: -moz-linear-gradient(#04acec,  #0186ba); 
 background: -webkit-gradient(linear, left top, left bottom, from(#04acec), to(#0186ba));
 background: -webkit-linear-gradient(#04acec,  #0186ba);
 background: -o-linear-gradient(#04acec,  #0186ba);
 background: -ms-linear-gradient(#04acec,  #0186ba);
 background: linear-gradient(#04acec,  #0186ba);
 color:red;
 border-radius:0px 3px 3px 0px;
 padding: 3px 0px 3px 5px; 
 margin:-4px -4px -4px -7px;
 width:180px;
}
</style>
and finally include this jquery code in the leftmenu page
<script type="text/javascript">
$(document).ready(function() {
  $currenturl = window.location.href;
  $("#left_menu_div ul li a").each(function() {
   $uurl = $(this).attr('href');
   if($(this).attr('href') == $currenturl){
    $(this).addClass('active');
    }
  });
});
</script>

its over... now you can see the active page link in different than all links.

Thank you...

1 comment:

  1. Nagendra
    Great article, but do you have a working example of this menu?
    Jack

    ReplyDelete