skip to Main Content

I want to to add a “active” Class to the navigation element from the current page. It works fine except for the index page, I want to keep the a href=”/” Link for the index site, because of SEO and aesthetics.

Any help?

$(function() {
  var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
  $(".menu-side a").each(function() {
    if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
      $(this).addClass("active");
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav class="menu-side">
  <a title="Startseite" href="/">Startseite</a>
  <a title="Über Mich" href="ueber_mich.html">Über Mich</a>
  <a title="Projekte" href="projekte.html">Projekte</a>
  <a title="Galerie" href="galerie.html">Galerie</a>
  <a title="Kontakt" href="kontakt.html">Kontakt</a>
  <a title="Impressum" href="impressum.html">Impressum</a>
</nav>

2

Answers


  1. You can always check if an active class is set, and if not, set the default one:

    $(function() {
      var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
      $(".menu-side a").each(function() {
        if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
          $(this).addClass("active");
      })
    
      if($(".menu-side a.active").length == 0) 
            $(".menu-side a:first").addClass('active');
    
    });
    a.active {color: green}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <nav class="menu-side">
      <a title="Startseite" href="/">Startseite</a>
      <a title="Über Mich" href="ueber_mich.html">Über Mich</a>
      <a title="Projekte" href="projekte.html">Projekte</a>
      <a title="Galerie" href="galerie.html">Galerie</a>
      <a title="Kontakt" href="kontakt.html">Kontakt</a>
      <a title="Impressum" href="impressum.html">Impressum</a>
    </nav>
    Login or Signup to reply.
  2. You can use sessionStorage to save the href of the element clicked, and when the page redirects, you reapply the class to the element with the saved href like so:

    $("nav a").click(function() {
      $(this) siblings().removeClass("active").addClass("active");
      sessionStorage.nowActive = $(this).attr('href');
    });
    
    $(document).ready(function() {
      if (sessionStorage.nowActive != "undefined") {
        $("nav a").each(function() {
          if ($(this).attr("href") == sessionStorage.nowActive) {
            $(this).addClass("active");
          }
        });
      }
    });
    

    Here is the JSFiddle of the code

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search