简体   繁体   中英

Bootstrap 4 - Highlight active nav-item/nav-link

I have a simple navigation bar in Bootstrap 4. I can't seem to get my jQuery code, even come close to add an "active" (class) to the nav-link class I click on.

 <script> $(document).ready(function () { $('.nav-link').click(function() { $('.nav-item').removeClass('active'); $(this).addClass('active'); console.log("Clicked..."); }); }); </script> 
  <nav class="navbar navbar-expand-sm navbar-dark fixed-top bg-dark"> <a class="navbar-brand" href="/">MySite</a> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="/menu1">Menu 1</a> </li> <li class="nav-item"> <a class="nav-link" href="/menu2">Menu 2</a> </li> </ul> </div> </nav> 

I think, the code would find active on the click event, and remove any active classes currently found, and add to the current nav-link class.

Can anyone help and explain why the above code, does highlight the element but then loses it? Is it because click occurs first, and then the page gets reloaded so any DOM changes are lost?

Since I am using Go, I have to pass a variable to the template, let's say, "Title" and add "active" to the class if Title matches the page I am rendering, renderTemplate is a custom function that uses RiceBox, FYI. I hope this helps someone:

func HomeHandler(w http.ResponseWriter, r *http.Request) {
  varMap := map[string]interface{}{
    "Title": "Home",
  }

  renderTemplate(w, "templates/index.html", &varMap)
}

HTML/Template (eg header.html which is loaded in index.html:

<nav class="navbar navbar-expand-sm navbar-dark fixed-top bg-dark">
  <a class="navbar-brand" href="/">My Site</a>
    <div class="collapse navbar-collapse" id="navbarCollapse">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item">
          <a class="nav-link {{ if eq .Title "Home" }}active{{ else }}{{ end }}" href="/">Home <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link {{ if eq .Title "Help" }}active{{ else }}{{ end }}" href="/help">Help</a>
        </li>
      </ul>
    </div>
</nav>

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