jtrdev
jtrdev

Reputation: 932

change li class depending on current webpage in MVC

I have an MVC app with a _Layout page, that gathers the main nav bar.

For each li class there is a specific class to needed to highlight the current page.

 <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-parent-item current-menu-item page_item current_page_item">
  @Html.ActionLink("Home", "index", "Home")<i class="fa fa-home hidden-xs"></i>
 </li>

How can I add this to other li classes when on that current page, while removing it from the Home when browsing away from it.

Upvotes: 3

Views: 181

Answers (1)

alex
alex

Reputation: 7453

One way you could accomplish this is to extract the URL from window.location.href, extract the relevant part of the URL via regex, then figure out some way to match this up with the appropriate nav button, and give this button a class that would highlight it - like:

.current-page {
    background-color: yellow;
}

A simpler solution would just be to add this class (or whatever) to the nav links on each individual view - something like this:

// <li id="about-me-section" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-parent-item current-menu-item page_item current_page_item">

$("#about-me-section").toggleClass("current-page");
$("#home-section").toggleClass("current-page");

Upvotes: 1

Related Questions