jasonkendall
jasonkendall

Reputation: 41

Adding class to primary-nav link when on a sub-page based on the url

I have primary navigation that are just "in-page" links on the home page. I also have a section of three pages for pricing that live as sub-pages with the urls: /pricing/basic-pricing.html, /pricing/pro-pricing.html and /pricing/pricing-premium.html.

On those three pages, I have a side-nav to get back-and-forth between those pages. So two navigation elements (primary-nav and side nav). When on a sub-page i.e. /pricing/basic-pricing.html, I would like the primary-nav link called "pricing" to have an active class.

I have it working with the code below, but was wondering if there is a better way in case I add more sub-pages in the future. I don't want to have to add more jQuery just to accommodate a new page. Right now it's only looking to see if the url contains the string 'pricing' in the href and then it adds the class to the 'pricing' link in the primary nav.

<nav class="primary-nav">
<ul class="menu collapse vertical large-horizontal">
   <li><a href="#features">features</a></li>
   <li><a href="#options">options</a></li>
   <li><a href="#pricing">pricing</a></li>
   <li><a href="#testimonials">testimonials</a></li>
   <li><a href="#contact">contact</a></li>
</ul>
</nav>
<ul class="vertical menu side-nav">
    <li><a href="{{root}}pricing/basic-pricing.html">Basic Pricing</a></li>
    <li><a href="{{root}}pricing/pro-pricing.html">Pro Pricing</a></li>
    <li><a href="{{root}}pricing/premium-pricing.html">Premium Pricing</a></li>
</ul>
$(document).ready(function () {
  $('.side-nav.menu a.is-active[href*="pricing"]').each(function () {
    $('.primary-nav .menu a[href$=pricing]').addClass('is-active');
  });
});

Upvotes: 1

Views: 247

Answers (1)

khofaai
khofaai

Reputation: 1357

you can use location global object to detect which url or uri you're in, here a link t it documentation : link example:

console.log(location.pathname) 
// /questions/56091860/adding-class-to-primary-nav-link-when-on-a-sub-page-based-on-the-url

in you case

// /pricing/basic-pricing.html

Upvotes: 1

Related Questions