简体   繁体   中英

Adding an active class to a ul list in nav

I am trying to add a position indicator to my nav bar using the snippet below (ie a border should appear when a list item is selected). I currently have the rest of my css code nested using scss in the form nav{ li{/*code here */} a{/ code here /}} and so on. When I add this active tag, nothing happens. Should I be formatting this differently with the active tag? Is there an easier way to do this? Why dosen't the active tag work? Thanks!!

HTML

<nav class="navbar navbar-main"> 
    <ul class="top-menu">
    <li id="home"><a href="#">HOME</a></li>
    <li id="about"><a href="#about">ABOUT</a></li>
    <li id="info"><a href="#media">MEDIA</a></li>
    <li id="social"><a href="#social">SOCIAL</a></li>
    </ul>
  </nav>

CSS

#nav ul li .active {
border-bottom:3px #FFF solid;
}

JS

$(function() {
     var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
     $("#nav ul li a").each(function(){
          if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
          $(this).addClass("active");
     })

Below code will find all <a> tag whose href attribute contains the current pathname.

$(function () {
        $("a[href*='" + location.pathname + "']").addClass("active");
})

For starters the css is not targeting the element correctly. Your css is looking for an element with an id of nav, which doesn't exist.

The nav element has two classes ( navbar and navbar-main ), so you can use either to start off the selection. Because the jquery is adding a class of active to a matching link, the css rule would need to include a . To actually see the border, you'd also need to set a display property. One that is used quite often is block eg:

.navbar ul li a.active {
  display:block;
  border-bottom:3px #FFF solid;
}

In the example I've provided below, I've updated the jquery to target a specific link, just for illustration purposes.

$(document).ready(function() {
  var pgurl = "#about"; //Using a static value for illustration purposes.
  $(".navbar ul li a").each(function(){
    if($(this).attr("href") == pgurl || $(this).attr("href") == '' ) {
      console.log($(this).attr("href"));
      $(this).addClass("active");
    }
  });
});

Fiddle example

This will work for you. That's how I use mine.

$(document).ready(function () {
      $(".top-menu > li > a[href*='" + location.pathname + "']").addClass('active'); //the .top-menu is your ul class
});(jQuery);

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