简体   繁体   中英

active class on menu and parent item

i have this HTML code for my menu:

<nav id="main-navigation" class="navigation-simple">
<ul>
    <li><a href="/">Home</a></li>           
    <li><a class="active-nav" href="">About Us</a>
    <ul>                        
        <li><a class="active-nav" href="about">About</a></li>               
        <li><a href="testimonials">Testimonials</a></li>
        <li><a href="meet-the-team">Meet The Team</a></li>  
    </ul>
    </li>
</nav>

i have added in the active-nav class but how can i automatically set the active class on parent and child items when the current URL is the href value of the link?

you need java script for this, jQuery is great for beginners!

It could be done like this:

var url = window.location.href;
$( "nav li a" ).each(function(index) { 
  if (url.indexOf($(this).attr('href')) >= 0){ 
    $(this).addClass('active-nav');
  }
});

line by line -

  1. get the current page url
  2. for each link in the navigation...
  3. check if its href is in the current url
  4. if it is, add the class 'active-nav'
  5. close if statement
  6. close for loop

Something like:

$(function() {
  $('#main-navigation a').each(function() {
    if(this.href.indexOf(window.location.pathname) === 0) {
      $(this).addClass('active-nav');
    } else {
      // case when something was set to active by the server
      $(this).removeClass('active-nav');
    }
  });
});

will do the job.

Make sure you make the if condition safe to your sites deeplinking implementation (eg GET params, anchors or multiple domains with same pathname are possible within your navigation).

You can use the .filter() method to find the appropriate link and add the required class:

$('#main-navigation li > a').removeClass('active-nav')
.filter(function() {
    return location.href.indexOf(this.href) > -1;
})
.addClass('active-nav') //add class to matched element(s)
//add class to parent(s) of matched, if any
.each(function() {
    $($(this).parents('a'), '#main-navigation').addClass('active-nav');
});

Also remember to close your first ul .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM