Mindless
Mindless

Reputation: 2357

Highlight current menu item asp.net using jquery

I want to highlight my current menu item in asp.net with jquery but I don't know why it is not working. Here is my code:

Site.css:

#menu {
    background: #292929;
}
#menu ul {
    margin: 0;
    padding: 0px 0px 0px 0px;
    list-style: none;
    line-height: normal;
    text-align: center;
}
#menu li {
    display: inline-block;
}
#menu a {
    display: block;
    padding: 0em 2em;
    line-height: 80px;
    letter-spacing: 1px;
    text-decoration: none;
    text-transform: uppercase;
    font-size: 1em;
    font-weight: 700;
    color: white;
}
#menu .current_page_item a {
    background: #01A9DC;
    color: #FFF;
}
#menu a:hover {
    text-decoration: none;
    background: #01A9DC;
    color: #FFF;
}
#menu a:active {
    background: #01A9DC;
    color: #FFF;
}

Site.Master:

<div id="menu" class="container">
    <ul>
        <li><a href="Home.aspx" accesskey="1" title="">Home</a></li>
        <li><a href="Softcare/SoftcareHome.aspx" accesskey="2" title="">Softcare</a></li>
        <li><a href="Softlearn/SoftlearnHome.aspx" accesskey="2" title="">Softlearn</a></li>
        <li><a href="Software/SoftwareHome.aspx" accesskey="2" title="">Software</a></li>
    </ul>
</div>

jQuery (1.7.1) inside <head>:

var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);

$("menu ul li a").each(function () {
    var href = $(this).attr('href');
    if (path.substring(0, href.length) === href) {
        $(this).closest('li').addClass('current_page_item');
    }
});

I also tried with javascript and it didn't work out well either, i think jquery is the best at doing this job, any advice is appreciated.

Upvotes: 0

Views: 2803

Answers (1)

Kevin Lynch
Kevin Lynch

Reputation: 24733

This is the flawless way I have always used jQuery to highlight the current menu item

$(function () {
  var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
  $('[href$="'+url+'"]').parent().addClass("active");
});

Upvotes: 1

Related Questions