Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight active menu item using jquery

I am having troubles highlighting my active menu items. I am using CSS for hover but what I understand from other posts is that a:active doesn't work with CSS?

This is what I have so done so far:

HTML

 <section id="nav">    
        <li><a class="nav" href="editorial.html">EDITORIAL</a></li>
        <li><a class="nav" href="places.html">PLACES</a></li>
        <li><a class="nav" href="people.html">PEOPLE</a></li>
        <li><a class="nav" href="architecture.html">ARCHITECTURE</a></li>
        <li><a class="nav" href="projects.html">PROJECTS</a></li>
        <li><a class="nav" href="published.html">PUBLISHED</a></li>
</section>

CSS

#nav{
width:100%;
text-align:center;
min-width:1300px;
height:80px;
position:absolute;
top:0;
left:0;
background:#fff;
list-style:none;
border-bottom: 1px solid #000;
}

#nav li{
display:inline;
}

#nav .nav{
display:inline-block;
background-color:#000;
color:#FFF;
font-family: 'Oswald', sans-serif;
letter-spacing:1px;
font-size:16pt;
line-height:18pt;
font-weight:400;
text-decoration:none;
margin-right: 3px;
margin-left: 3px;
margin-top:35px;
padding:0px 3px 2px 3px;
}

#nav .nav:hover{
background:#FFFF00;
color:#000;
}

.active{
background:#FFFF00;
color:#000;
}

JQUERY

  <script>
 $(document).ready(function() { 
  $("#nav li .nav").click(function ( e ) {
e.preventDefault();
$("#nav li a.active").removeClass("active"); //Remove any "active" class  
$(this).addClass("active"); //Add "active" class to selected tab  

// $(activeTab).show(); //Fade in the active content  
});
});

Thanks in advance!

like image 725
krubkiewicz Avatar asked Aug 14 '14 20:08

krubkiewicz


People also ask

Which event is used to highlight menu items?

The MenuItemClick event is raised when a menu item is clicked in a Menu control.


1 Answers

I used following code. Late answer, but I hope this will help someone.

// This will work for both relative and absolute hrefs
function active_menu() {   
    var url = window.location.href;
    $('.nav a').filter(function() {
        return this.href == url;
    }).addClass('selected');
}
like image 189
Vajira Lasantha Avatar answered Nov 15 '22 10:11

Vajira Lasantha